HTML maxlength Attribute

Description

The maxlength attribute in HTML is used to specify the maximum number of characters that a user can input into an <input> or <textarea> element. It helps in controlling the amount of data a user can enter, making it particularly useful for fields where the input length needs to be restricted, such as a ZIP code or a phone number field.

When the maxlength attribute is set on an element, it limits the number of characters that can be entered in that element to the specified value. If a user attempts to enter more characters than allowed, the extra characters will not be accepted, effectively preventing the user from exceeding the specified limit.

The attribute is added directly to the HTML tag of the input or textarea element, with its value representing the maximum allowed characters. For example, setting maxlength="5" on an input field would restrict the user to a maximum of 5 characters.

It's important to note that while the maxlength attribute helps in front-end validation, ensuring the security and integrity of the data on the backend is also essential. Always validate and sanitize user inputs on the server-side to protect against malicious data submissions.

Syntax

<input maxlength="number">

Values

  • numberThe maximum numeric value in an input field.

Applies To

The maxlength attribute can be used on the following html elements.

Example

<form action="formscript.php">
<label for="username">Username:</label><br>
<input type="text" id="username" name="username" maxlength="20">
<br><br>
<label for="comment">Comment:</label><br>
<textarea id="comment" name="comment" maxlength="250"></textarea>
<br><br>
<button type="submit">Submit</button>
</form>

Browser Support

The following table will show you the current browser support for the HTML maxlength Attribute.

Desktop
Edge Chrome Firefox Opera Safari
121112.11
Tablets / Mobile
Chrome Firefox Opera Safari Samsung Webview
18412.1114

Last updated by CSSPortal on: 26th March 2024