Skip to: content, navigation

maxlength (HTML attribute)

Spec
Depr. Version
No HTML 2
Browser support (more…)
IE5.5+ FF1+ SA1.3+ OP9.2+
Full Full Full Full

Syntax

maxlength="number"

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.

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>

Value

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

Compatibility

Internet Explorer Firefox Safari Opera
5.5 6.0 7.0 1.0 1.5 2.0 1.3 2.0 3.0 9.2 9.5
Full Full Full Full Full Full Full Full Full Full Full

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

User-contributed notes

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

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

Search