[wp-trac] [WordPress Trac] #34893: Improve Customizer setting validation model
WordPress Trac
noreply at wordpress.org
Mon Dec 7 08:44:44 UTC 2015
#34893: Improve Customizer setting validation model
-------------------------------------+--------------------------
Reporter: westonruter | Owner: westonruter
Type: enhancement | Status: accepted
Priority: normal | Milestone: 4.5
Component: Customize | Version: 3.4
Severity: normal | Resolution:
Keywords: has-patch needs-testing | Focuses: javascript
-------------------------------------+--------------------------
Changes (by westonruter):
* keywords: needs-patch => has-patch needs-testing
* owner: => westonruter
* status: new => accepted
* milestone: Future Release => 4.5
Comment:
I have implemented this in a feature plugin called
“[https://github.com/xwp/wp-customize-setting-validation Customize Setting
Validation]”.
To do server-side validation of a setting, implement a setting sanitizer
that returns `null` or a `WP_Error` object:
{{{#!php
<?php
$wp_customize->add_setting( 'year_established', array(
'type' => 'option',
'sanitize_callback' => function ( $value ) {
$value = intval( $value );
// Apply strict validation when the sanitize callback is
called during.customize_validate_settings.
if ( doing_action( 'customize_validate_settings' ) && (
$value < 1900 || $value > 2100 ) ) {
return new WP_Error( 'invalid_value', __( 'Year
must be between 1900 and 2100.' ) );
}
$value = min( 2100, max( $value, 1900 ) );
return $value;
}
) );
}}}
By returning `null`, the Customizer will display a generic error message.
By returning `WP_Error`, the specific message can be provided.
The validation error message can also be set programmatically by JS by
calling `control.validationMessage.set()`,
for example from an extended `control.setting.validate()` method. The
`validationMessage` is inspired by HTML5.
For a demonstration of the functionality made possible with this
Customizer setting validation API,
including how to do client-side validation, see the
“[https://gist.github.com/westonruter/1016332b18ee7946dec3
Customize_Validate_Entitled_Settings]” plugin. It will validate that the
Site Name (`blogname`), nav menu item titles, and widget titles are all
fully populated. The validation is done both on the client and on the
server.
--
Ticket URL: <https://core.trac.wordpress.org/ticket/34893#comment:1>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform
More information about the wp-trac
mailing list