Validate an Element v3.21
While each input type can define its own validation rules and expose them through input options (e.g. required), you can also define validation rules for whole elements. This is useful to express more complex, imperative validation logic, in particular when the validity of an input depends on the value of another input.
An element's validation handler can be defined by calling setValidationHandler on the element definition. This handler will be called after all internal input validations have been performed.
As its arguments, the handler receives:
- A record of the element's properties + values.
- A record of the element's current properties + error messages. Modify this object to set error messages for specific properties. Set the
$property to set a general error message for the whole element. - The previous validation result (boolean).
If the validation handler returns a boolean value, that will override the previous validation result.
document.addEventListener('wpce_instance_added', function (event) {
const editor = event.detail.instance
editor.definition.setValidationHandler(
'time-controlled-content',
function (values, messages) {
if (values.end < values.start) {
messages.start = 'Start must be before end'
messages.end = 'End must be after start'
return false
}
}
)
})TIP
Validation handlers may return a Promise. However, speed and responsiveness is a major WPCE feature, so try to use this sparingly.