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:
- Sanitize and validate the
$value
- Prevent the settings from being saved if invalid.
- Retain the entered value in the form field
Is there any workaround for this?