Module Monday: Maxlength JS

How to Add Character Counters to Form Fields and Avoid Drupal's "Error on Submit" Messages

Text fields built using Drupal's FormAPI have always supported a "Max Length" property; set it, and Drupal will kick back an error when someone submits too much data in the form field. CCK and FieldAPI support that property as well, allowing you to specify just how much text a user can enter into the fields you've defined. However, the standard Drupal "error on submit" behavior can be annoying for end users who type their novel only to see errors when they submit. Enter Maxlength JS, a simple module that adds jQuery frosting to the maximum-length cupcake.















Screenshot of MaxLength settings

Configuring the module couldn't be simpler: turn it on, and every CCK or FieldAPI text field will get a new "Maxlength JS" option in addition to its normal "Max Length" field. Enter in a number here, and the module will add a client-side character count timer to the field, telling users exactly how much space they have left. If you're defining your own form fields in a module, you can get the same effect by setting the #maxlength_js property on your own form fields. If the MaxLength JS module isn't enabled, the property will have no effect and users will get the default Drupal behavior.















Screenshot of a MaxLength restricted body field

MaxLength is currently available for Drupal 6 and 7, and it's compatible with most WYSIWYG editors as well. There are currently plans to merge the module with the similar MaxLength project, so keep your eyes open for future developments!

Get in touch with us

Tell us about your project or drop us a line. We'd love to hear from you!