Introduction
Would you like to limit characters for the Rich Text form field? The Single Line Text and Paragraph form fields, have a built-in feature that allows you to limit the characters or words for this field. To learn more about this, please take a look at this helpful guide.
However, if you wanted to limit the characters for the Rich Text form field, you can easily use a small snippet and in this tutorial, we’re going to show you how.
Creating the form
Begin by creating a new form and adding your fields, including at least one Rich Text form field.
If you need any assistance in creating your form, please see this documentation.
Adding the snippet
Now it’s time to add the snippet to your site. For any assistance on how and where to add snippets to your site, please see this tutorial.
/** * Add Rich Text field validation. * * @link https://wpforms.com/developers/how-to-limit-characters-for-the-rich-text-field/ */ function wpf_dev_validate_richtext( $field_id, $field_submit, $form_data ) { // Optional, you can limit to specific forms. Below, we restrict output to form #3382. if ( absint( $form_data[ 'id' ] ) !== 3382 ) { return $field_id; } // Set the maximum character limit here $max_characters = 150; // Check for character limit $char_count = mb_strlen( $field_submit, 'UTF-8' ); if ( $char_count > $max_characters ) { $error_message = sprintf( esc_html__( 'Character limit exceeded. The maximum number of characters allowed is %d.', 'wpforms' ), $max_characters ); wpforms()->process->errors[ $form_data['id'] ][ $field_id ] = $error_message; } } add_action( 'wpforms_process_validate_richtext', 'wpf_dev_validate_richtext', 10, 3 );
This snippet will only look at the form ID 3382, you’ll need to update this ID number to match your own form ID. If you’re not sure where to find your form ID number, please review this tutorial.
The next part of the snippet is looking at the $max_characters variable which is set to have a limit of 150 characters. As the snippet is processed, it will look and count the characters (UTF-8 format) in this field and if the number of characters exceeds the 150 limit, when the form submits, it will display an error.
And that’s all you need to limit the characters for the Rich Text field. Would you also like to block users from entering a URL in this field as well? Take a look at our tutorial on How to Block Domains From Your Text Fields.
Related
Action Reference: wpforms_process_validate_richtext