The maxlength attribute is used to define the maximum number of characters allowed in an input field. It helps restrict the length of user input.
- Limits the number of characters a user can enter.
- Commonly used with text-based input fields like text, password, and email.
- Helps in input validation and controlling data size.
Syntax:
<input maxlength="number">- 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
Here are some examples of using maxlength attribute:
Example 1: Limiting Username and Password Length
The maxlength attribute is used within <input> elements to restrict the length of text inputs for username and password fields.
<!--Driver Code Starts-->
<!DOCTYPE html>
<html>
<head>
<title>HTML input maxlength Attribute</title>
</head>
<!--Driver Code Ends-->
<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>
<!--Driver Code Starts-->
</html>
<!--Driver Code Ends-->
Example 2: Limiting Email Address Length
Here, the maxlength attribute limits the length of an email input field to 30 characters.
<!--Driver Code Starts-->
<!DOCTYPE html>
<html>
<head>
<title>HTML input maxlength Attribute</title>
</head>
<!--Driver Code Ends-->
<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>
<!--Driver Code Starts-->
</html>
<!--Driver Code Ends-->