HTMLintermediate 8 min
Required fields, patterns and input types that check themselves, with no JavaScript.
How to make the browser check input for you using required, minlength, min, max and pattern.
Catching a mistake before the form is sent saves time and frustration. Built-in validation works without any JavaScript, and it is accessible by default.
Validation means checking that the input is acceptable. HTML has attributes for the common checks:
required: the field cannot be empty.type="email" and type="url": the value must look like an email or web address.minlength and maxlength: limits on text length.min and max: limits on numbers and dates.pattern: a regular expression the text must match, such as [0-9]{6} for exactly six digits.title: the message hint shown when the pattern fails.When the user presses submit and something is invalid, the browser stops, focuses the first bad field and shows a message.
required and must be 3 to 10 characters.pattern="[0-9]{4}" means exactly four digits. title is the explanation shown to the user.Add a required email field with type="email", and try submitting hello to see the error.
title, so the user does not know what is expected.maxlength on number fields. Use min and max for numbers.required and then wondering why empty values are accepted.required, min, max, minlength, pattern and input types validate for free.title to explain a pattern.Next: tags that give structure meaning.
<form>
<p>
<label for="user">Username (3 to 10 characters)</label><br>
<input id="user" name="user" required minlength="3" maxlength="10">
</p>
<p>
<label for="age">Age (18 to 99)</label><br>
<input id="age" name="age" type="number" min="18" max="99" required>
</p>
<p>
<label for="pin">PIN (exactly 4 digits)</label><br>
<input id="pin" name="pin" pattern="[0-9]{4}" title="Four digits" required>
</p>
<button type="submit">Join</button>
</form>