Skip to: content, navigation

by Ian Lloyd

maxlength (HTML attribute)

Browser support full matrix
IE5.5+ FF1+ Saf1.3+ Op9.2+
Full Full Full Full
Spec
Depr. Version
No HTML 2
maxlength="number"

Example

This maxlength attribute restricts entries in this password field to a maximum of four characters:

<form>
  <label for="pin">Your 4-digit PIN:</label>
  <input type="password" name="pin" id="pin"
      maxlength="4" size="6"/>
  ⋮
</form>

Description

While it’s possible to use JavaScript to validate form data entry, this approach can’t be relied upon (JavaScript may be disabled, and form data may not be trustworthy if the client has been affected by a nefarious script). Server–side validation is a much safer option, and could be used, among other things, to check that the amount of data submitted isn’t too long. The maxlength attribute provides a means for reducing the likelihood that too much data will be sent to the server for processing, and also provides some degree of usability enhancement—users can clearly see when they’ve reached the maximum character length for an input, as although they’re typing, nothing more is being entered into the field.

Value

The value for this attribute is a number which represents the total characters that can be submitted.

Compatibility

IE5.5Full
6.0Full
7.0Full
Firefox1.0Full
1.5Full
2.0Full
Safari1.3Full
2.0Full
3.0Full
Opera9.2Full

It causes no compatibility issues, and has excellent support across all tested browsers.

User-contributed notes

ID:
#1
Date:
Fri, 28 Mar 2008 11:13:55 GMT
Contributed by:
AutisticCuckoo

A nefarious script would circumvent a MAXLENGTH attribute as easily as it would JavaScript validation. MAXLENGTH must not be relied upon. It's simply a usability enhancement for users, who won't be able to type in something akin to "War and Peace" only to receive a validation error that says, 'Max 4 characters'.

Add a note

To post a note on this topic, please log in with your SitePoint username and password. If you don't have an account yet, you can create a new account for free.

Related Products

The Principles of Beautiful Web Design

Best Seller!

You don’t need to go to Art School to design great looking web sites!

Book Cover: The Principles of Beautiful Web Design

Download the FREE sample chapters