maxlength (HTML attribute)
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
| IE | 5.5 | Full |
|---|---|---|
| 6.0 | Full | |
| 7.0 | Full | |
| Firefox | 1.0 | Full |
| 1.5 | Full | |
| 2.0 | Full | |
| Safari | 1.3 | Full |
| 2.0 | Full | |
| 3.0 | Full | |
| Opera | 9.2 | Full |
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
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.

