How to Set a Minimum Number of Characters on a Text Form Field

Overview

Would you like to set a minimum number of characters for your Single Line Text form field? Inside the form builder, you can already set a maximum number for this field. However, using a little JavaScript snippet you can also set a minimum number as well. In this tutorial, we’ll show you the JavaScript code snippet needed to complete this.

Setup

You can already set up your forms to have a maximum number of characters for your Single Line Text field by following the steps in this tutorial.

1) Setting up the form

First, set up your form to add a Single Line Text field and set the maximum number to match your needs. In our example, we’ve set our Limit Length to ten characters.

Set the maximum characters to 10

2) Adding the JavaSript

Next, you’ll need to copy the code snippet below and add it to your site.

In our example below, we’re requiring a minimum of five characters.

/**
 * Set minimum number of characters on Single Line Text
 *
 * @link https://wpforms.com/developers/how-to-set-a-minimum-number-of-characters-on-a-text-form-field/
 *
 */
function wpf_dev_char_min() {
	?>
	<script type="text/javascript">
        jQuery(document).ready(function ($) {
            $(".wpf-char-min input").attr('minlength', '5'); // Change this number to match your needs
            $(".wpf-char-min textarea").attr('minlength', '5'); //Change this number to match your needs
        });
	</script>
	<?php
}
add_action( 'wpforms_wp_footer_end', 'wpf_dev_char_min' );


3) Adding the CSS Class

Finally, open the form builder, click the field to open its Field Options panel and open the Advanced Options section.

Next, add wpf-char-min to the CSS Classes field.

Set the CSS class to set the minimum number of characters

And that’s it! You’ve now set a minimum number of characters for the text field as well as a maximum number.

If the minimum number of characters is not set, an error will appear

Would you like to set a minimum and maximum number for checkboxes too? Take a look at our tutorial on How to Set a Minimum and a Maximum Number of Choices for a Checkbox.

FAQ

Q: Can I use this on Paragraph form fields as well?

A: Absolutely. Following the same tutorial above and just add a Paragraph Text form field to your form and apply the same JavaScript code and CSS class and you’d have a minimum set on that form field as well.

Action reference: wpforms_wp_footer_end