After digging in the setting API I found the answer. Method 1 was correct, but the notification should not be done by hooking to admin_notices
, rather by the function add_settings_error
add_action ('pre_update_option_my_var', function( $new_value, $old_value) {
//Do my validation
$valid = ( 'correct_value' == $new_value );
if ( !$valid ) {
//This fixes the issue
add_settings_error( 'my_var', $error_code, $message );
}
return ($valid)? $new_value : $old_value;
});
In order to display them, this also needs to be added at the beginning of the settings page:
<h2>The heading of my settings page</h2>
<?php settings_errors(); ?>