Required and pattern
Use required and pattern for browser-side validation.
What is client-side validation?
When a form holds wrong data, a round-trip to the server is slow. Client-side validation lets the browser check fields before the form is submitted. HTML does it with a few attributes: required stops an empty field, pattern demands the typed text match a regular expression. This cuts needless requests to the server; for security the server must still check too.
Enforcing format with pattern
The pattern attribute takes a regular expression and the browser checks that the typed text matches it. For example pattern="[0-9]{5}" asks for exactly five digits, pattern="[A-Z]{2}-[0-9]{4}" for two uppercase letters, a dash and four digits. If the text doesn't match, the browser blocks submission and shows a warning. Use the title attribute to tell the user the expected format briefly.
Exercise Add a required email and a pattern-locked phone to the form
Add two fields to the form below:
- An email field (
type="email"), required - A phone field (
type="tel"), required and withpattern="[0-9]{10}"to enforce 10 digits
Give each a <label>; the for and id values must match.
Show example solution
<form action="/signup" method="post">
<label for="email">Email</label>
<input type="email" id="email" required>
<label for="phone">Phone</label>
<input type="tel" id="phone" pattern="[0-9]{10}" required>
</form>
Test yourself
-
What does adding required to an input do?
<input type="text" required>- Stops the field being left empty
- Makes the field accept only numbers
- Fills the field automatically
- Hides the field
Show answer
Stops the field being left empty — Correct. required blocks form submission when the field is empty.
-
Complete the five-digit ZIP code pattern
<input type="text" pattern="____" title="5-digit ZIP code">Show answer
<input type="text" pattern="[0-9]{5}" title="5-digit ZIP code"> -
Match each attribute to its role
- required
- Blocks empty field
- pattern
- Checks text format
- title
- Tells expected format
- type
- Sets the field kind