HTML input maxlength Attribute
The maxlength attribute in the HTML <input> element is used to define the maximum number of characters that can be entered into the field. If no value is specified, or if an invalid value is provided, the input field will have no maximum length.
The length is determined in UTF-16 code units, which typically correspond to the number of characters.
Syntax
<input maxlength="number">
Attribute Value
Attribute Value | Description |
---|---|
number | It contains a single value number which allows the maximum number of characters in <input> element. Its default value is 524288. |
Examples of Using the maxlength Attribute
Example 1: Limiting Username and Password Length
In this example, the maxlength attribute is used within <input> elements to restrict the length of text inputs for username and password fields.
<!DOCTYPE html>
<html>
<head>
<title>HTML input maxlength Attribute</title>
</head>
<body>
<h1>GeeksforGeeks</h1>
<h2>HTML <input> maxlength Attribute</h2>
<form action="#">
Username:
<input type="text"
name="username"
maxlength="12" />
<br />
<br />
Password:
<input type="text"
name="password"
maxlength="10" />
<br />
<br />
<input type="submit"
value="Submit" />
</form>
</body>
</html>
Output:
Example 2: Limiting Email Address Length
Here, the maxlength attribute limits the length of an email input field to 30 characters.
<!DOCTYPE html>
<html>
<head>
<title>HTML input maxlength Attribute</title>
</head>
<body>
<h1>GeeksforGeeks</h1>
<h2>HTML <input> maxlength Attribute</h2>
<form action="#">
Email:
<input type="email"
name="email"
maxlength="30"
style="width: 350px" />
<br /><br />
<input type="submit"
value="Submit" />
</form>
</body>
</html>
Output: