The maxlength attribute limits the number of characters users can enter in an input field. Once the maximum is reached, the browser prevents further typing. For example, maxlength equals 10 allows only 10 characters. Unlike other validation attributes that check on submission, maxlength prevents exceeding the limit during typing. This provides immediate feedback and prevents user frustration. Maxlength works with text, email, password, search, tel, and url input types. It also works with textarea elements. You can combine maxlength with minlength to enforce both minimum and maximum lengths. For example, passwords might require minlength equals 8 and maxlength equals 50. The maxlength attribute is useful for database fields with character limits, social media posts, usernames, or any input with length restrictions.
Example code
<!-- Username with maxlength -->
<form>
<label for="username">Username (max 15 chars):</label>
<input type="text"
id="username"
name="username"
maxlength="15"
required>
</form>
<!-- Tweet-like input -->
<form>
<label for="tweet">Message (max 280 chars):</label>
<textarea id="tweet"
name="message"
maxlength="280"
rows="4"></textarea>
<p id="char-count">0 / 280</p>
</form>
<!-- Password with min and max length -->
<form>
<label for="password">Password:</label>
<input type="password"
id="password"
name="password"
minlength="8"
maxlength="50"
required>
<small>8-50 characters required</small>
</form>
<!-- Phone number -->
<form>
<label for="phone">Phone (10 digits):</label>
<input type="tel"
id="phone"
name="phone"
maxlength="10"
pattern="[0-9]{10}"
required>
</form>