wordpress - mark wp_editor required field in form
I am working on a frontend form for wordpress and I have added
wp_editor
for text area in my form, below is the code I have added. Is there any way I can mark this field as a Required field just like HTML5 required parameter?
<?php
$settings = array(
'wpautop' => false,
'media_buttons' => true,
'textarea_rows' => 5,
'tinymce' => true,
'teeny' => true,
'textarea_name' => 'main_Content',
'quicktags' => false,
'editor_height' => 300
);
$content = '';
$editor_id = 'main_Content';
wp_editor(stripslashes($content), $editor_id, $settings);
?>
Solutions
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)
or else
You can add a filter to the editor html
add_filter( 'the_editor', 'add_required_attribute_to_wp_editor', 10, 1 );
function add_required_attribute_to_wp_editor( $editor ) {
$editor = str_replace( '<textarea', '<textarea required="required"', $editor );
return $editor;
}
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.
- When creating the editor, add a class that is unique to my plugin and indicates that content is required in this editor.
- Hook a function to 'the_editor'.
- This function will check if the markup for the editor contains my custom class. If so, it adds the required attribute.
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 10.1 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;
}