Length Constraints: minlength and maxlength
You'll learn how to enforce minimum and maximum character limits on user input to ensure data quality and consistency.
The Core Idea
When users type into text fields or textareas, you often need to control how short or long their input can be. The minlength and maxlength attributes let you set these boundaries directly in your HTML. Think of them as gatekeepers: maxlength stops users from typing beyond a limit (like Twitter's character counter), while minlength requires a certain amount of content before the form can be submitted.
How They Work
Add these attributes to <input> elements (of type text, email, password, etc.) or <textarea> elements:
<input type="text" minlength="3" maxlength="20" required>
This input requires at least 3 characters and won't accept more than 20.
<textarea minlength="10" maxlength="500"></textarea>
This textarea needs a minimum of 10 characters and caps at 500.
Important Behavior
maxlengthphysically prevents typing beyond the limit—users can't exceed itminlengthonly triggers validation on form submission—it won't stop users from typing less, but the form won't submit- Both work with the Constraint Validation API you've learned
- Empty fields pass
minlengthvalidation unless also markedrequired
<form>
<label>Username (3-15 characters):</label>
<input type="text" name="username" minlength="3" maxlength="15" required>
<button type="submit">Submit</button>
</form>
Key Takeaway: Use minlength and maxlength to enforce character limits—maxlength blocks excess typing immediately, while minlength validates on submission to ensure sufficient input length.