1. Home
  2. Snippets
  3. Limit number of characters for a text field

Limit number of characters for a text field

Heads up!

This article contains javascript code and is intended for developers. We offer this code as a courtesy, but don't provide support for code customizations or 3rd party development.

For extra guidance, please see WPBeginner's tutorial on adding custom code.


When creating an HTML form, it’s possible to add a maxlength attribute to any input box. Since WPForms generates all field HTML for you, you can instead add the maxlength attribute using jQuery.

We’ll load this jQuery within PHP so that it can be added right into functions.php or wherever you choose to keep custom PHP on your site.

Note: For shorter character limits, or other format requirements, please consider using a custom input mask instead of the code below.

 * Limit number of characters allowed for an input/textarea field
 * Apply the class "wpf-char-limit" to the field to enable.
function wpf_dev_char_limit() {
	<script type="text/javascript">
			$('.wpf-char-limit input').attr('maxlength',40); // Change number to character limit (input fields)
			$('.wpf-char-limit textarea').attr('maxlength',40); // Change number to character limit (paragraph fields)
add_action( 'wpforms_wp_footer', 'wpf_dev_char_limit' );

This code will apply a maximum length of 40 characters to any input field with a CSS class named wpf-char-limit. When changing this limit, be sure to do so in two places.

To add this class to a field, you’ll need to open the form builder, click the field to open its Field Options panel, and open the Advanced Options section.

Add character limit class to input field

Since this code will simply enforce a character limit, it’s also a good idea to let your users know about this limit within the field description.

Updated on July 24, 2018

Was this article helpful?