Читать книгу Professional WordPress Plugin Development - Brad Williams - Страница 92
Validating User Input
ОглавлениеThere is still one callback function to define, pdev_plugin_validate_options()
, as mentioned earlier when registering the settings.
In this example, users are asked to enter text, so your validation function simply makes sure that the input contains only letters.
<?php // Validate user input (we want text and spaces only) function pdev_plugin_validate_options( $input ) { $valid = array(); $valid['name'] = preg_replace( '/[^a-zA-Z\s]/', '', $input['name'] ); return $valid; } ?>
To validate the user input as letters only, a simple pattern matching (also known as regular expression) that strips all other characters is used here. This regex pattern also supports spaces between names.
This function is passed the $_POST
data as a parameter. For enhanced security, start creating a new empty array named $valid
and collect in this array only the values you are expecting. This way, if for some reason an unanticipated field is submitted in the form, your function not only validates the information you want but also blocks everything else. Refer to Chapter 4 for more tips and functions about data validation.