Minlength and maxlength
Learn to limit text length with minlength and maxlength.
Text length: minlength and maxlength
For text fields, length is bounded by minlength and maxlength. minlength="8" asks for at least 8 characters, maxlength="64" at most 64. Put both on a password field and the browser rejects short or overly long passwords. This gives a basic length check before the data reaches the server.
min/max vs minlength/maxlength
These four are often mixed up. min and max bound the numeric value; they work on fields like type="number" or type="range". minlength and maxlength bound the character count; they work on text fields (type="text", type="password", <textarea>). An age field gets min="18"; a username gets minlength="3".
Exercise Add length bounds to a password field
Add a password field to the sign-up form. It must carry:
type="password"minlength="8"(at least 8 characters)maxlength="64"(at most 64 characters)required- A
<label>with matching for↔id
Show example solution
<form action="/signup" method="post">
<label for="pwd">Password</label>
<input type="password" id="pwd" minlength="8" maxlength="64" required>
</form>
Test yourself
-
What does maxlength="20" do on a text input?
<input type="text" maxlength="20">- Require at least 20 characters
- Keep the value under 20
- Cap input at 20 characters
- Make the field 20px wide
Show answer
Cap input at 20 characters — Correct. maxlength="20" caps the input at 20 characters.
-
Complete the maximum characters for a username
<input type="text" id="user" ____ required>Show answer
<input type="text" id="user" maxlength="20" required> -
Match each attribute to the field it applies to
- min
- type="number"
- max
- type="range"
- minlength
- type="text"
- maxlength
- type="password"