What is maxlength? Understanding the HTML maxlength Attribute
The maxlength attribute in HTML controls the maximum number of characters a user can enter into an or element. This is crucial for data validation and maintaining consistent data sizes in your application.
The attribute's value must be a non-negative integer. This length is based on UTF-16 code units, which often corresponds to characters but might differ for certain Unicode characters. If maxlength is not specified, or if an invalid value is provided, there is no enforced maximum length.
How to Use Implementing maxlength in Your HTML
To use maxlength, simply add the attribute to your or tag: . This limits the input to 50 characters.
The length is evaluated based on UTF-16 code units. Make sure to account for this when dealing with different character sets. Always consider your users and the data they'll be providing when setting maxlength.
Constraint Validation maxlength and
The maxlength attribute plays a significant role in constraint validation. If the input's value exceeds the specified maxlength, the input will fail the validation check.
Browser behavior: While browsers generally prevent users from exceeding the limit, situations can occur where the entered text's length might surpass the maxlength value (e.g., through JavaScript manipulation). In such scenarios, the validity.tooLong property of the input element will be set to true.
“The maxlength attribute is a simple yet effective way to control user input and ensure data integrity.
MDN Web Docs Contributors
Interactive Features
Explore Related Concepts
Form Validation
Learn about other form validation techniques beyond maxlength, including required fields and data type validation.
Input Types
Discover various HTML input types (text, email, number, etc.) and their unique attributes for user input.
Textarea Element
Understand the differences and similarities between the <textarea> and <input> elements, including the application of maxlength.
Example Demonstrating maxlength
Here's an example demonstrating maxlength usage:
`html
`
This example limits the username input to a maximum of 15 characters.