Читать книгу Professional WordPress Plugin Development - Brad Williams - Страница 96

Improving Feedback on Validation Errors

Оглавление

The validation function you've previously defined could be slightly improved by letting the users know they have entered an unexpected value and that it has been modified so that they can pay attention to it and maybe amend their input.

The relatively unknown function add_settings_error() of the Settings API can handle this case. Here's how it is used:

<?php add_settings_error( setting, code, message, type ); ?>

This function call registers an error message that displays to the user. add_settings_error() accepts the following parameters:

 setting: Title of the setting to which this error applies

 code: Slug name to identify the error, which is used as part of the HTML ID tag

 message: Formatted message text to display, which is displayed inside styled <div> and <p> tags

 type: Type of message, error or update

You can improve the validating function with a user notice if applicable, as shown here:

<?php function pdev_plugin_validate_options( $input ) { $valid['name'] = preg_replace( '/[^a-zA-Z\s]/', '', $input['name'] ); if( $valid['name'] !== $input['name'] ) { add_settings_error( 'pdev_plugin_text_string', 'pdev_plugin_texterror', 'Incorrect value entered! Please only input letters and spaces.', 'error' ); } return $valid; } ?>

The function now compares the validated data with the original input and displays an error message if they differ (see Figure 3‐5).


FIGURE 3‐5: Error message

Professional WordPress Plugin Development

Подняться наверх