1

I'm using the Settings API to save the settings of my plugin. I want a positive integer value from the settings field.

register_setting( $option_group, $option_name . '_number', 'sanitize_number_callback' );

function sanitize_number_callback( $value ) {

    $filtered = sanitize_text_field( $value );

    if ( preg_match('/\A[1-9]\d*\Z/', $filtered) ) {
        return $filtered;
    }
    else{
        $type = 'error';
        $message = 'Number must be a positive integer';

        add_settings_error(
            'my_settings',
            esc_attr( 'settings_updated' ),
            $message,
            $type
        );
    }
}

Now if the user enters a non integer value and tries to save the settings, the error is shown and an empty value is saved into the database overwriting the previously saved value, because there is no return statement when condition is false. And the field value is also made empty.

Now if I return the sanitized value which is not valid, then it's still saved in the database!

I don't know how it makes sense that an error has been shown and the settings are still saved! Quite Strange!

What I want:

  1. Sanitize and validate the $value
  2. Prevent the settings from being saved if invalid.
  3. Retain the entered value in the form field

Is there any workaround for this?

0

You'd do it something like this:

function sanitize_number_callback ($input){

    if( !preg_match( '/...regex for valid here.../', $input ) ){
        add_settings_error(
            'my_option',
            esc_attr( 'my_option' ), //becomes part of id attribute of error message
            __( 'Number must be a positive integer', 'wordpress' ), //default text zone
            'error'
        );
        $input = get_option( 'my_option' ); //keep old value
    }

    return $input;
}

Basically, if validation fails, you return the old saved value. Your validation is completely constraining the input values so no need to sanitize as well.

I don't know how you'd hold the incorrect value in the form field if validation failed. As far as I can see, the settings API doesn't allow for it directly. Someone else may be able to provide a solution?

  • Yes, that's how I retain the old saved value.Yes there is no way in Settings API to retain the incorrect value. – ManzoorWani May 3 '17 at 7:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.