I want to add HTML5 required for the client side validation on textarea generated by
<?php
$content = '';
$editor_id = 'YOURID';
wp_editor( $content, $editor_id );
?>
What is the best way to add required
on textarea?
Thank you.
The visual editor is not a textarea, it is an iframe, therefor even if you could set an attribute it will do nothing. You can set the attribute on the hidden textarea that will be sent to the server but since it is hidden I am not sure how an alert about it not being filled will be displayed and it might be different between browsers (it is hidden so there is no obvious visual anchor for the display of the alert)
I have done the following successfully for a plug-in that uses several visual editors (only some of which are required) on an Admin Screen.
I am able to style the field using
textarea[required]:invalid
and the form generates an error if it is submitted while this field is empty (though I've only tested in Safari so far).
Sample code is below (This code was taken from a much larger class). First, an excerpt from the function that builds the editor.
$addlClass = ($required) ? 'my-required-field' : '';
$settings = array(
'media_buttons' => false,
'textarea_name' => $fieldName,
'editor_class' => $addlClass
);
wp_editor($cleanFld, $fieldId, $settings);
Then, my hook:
add_action('the_editor', array($this, 'CheckIfEditorFieldIsRequired'));
Finally, that function:
public function CheckIfEditorFieldIsRequired($editorMarkup)
{
if (stripos($editorMarkup, 'my-required-field') !== false) {
$editorMarkup = str_replace('<textarea', '<textarea required', $editorMarkup);
}
return $editorMarkup;
}