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.

Dismiss

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.

/**
 * Limit number of characters allowed for a field
 * Apply the class "wpf-char-limit" to the field to enable.
 *
 */
function wpf_dev_char_limit() {
	?>
	<script type="text/javascript">
		jQuery(function($){
			$('.wpf-char-limit').attr('maxlength',40); // Change number to character limit
		});
	</script>
	<?php
}
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.

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 November 20, 2017

Was this article helpful?