How to validate an email, a phone or a field format
Short answer
Give the field a suitable type — the browser checks the format on submit by itself:
<form>
<input type="email" placeholder="Email" required>
<button>Send</button>
</form>Type anna without the at sign and press "Send" — the form is not submitted. The url type checks website addresses the same way.
A custom format with pattern
For everything else there is pattern — a regular expression the whole value must match. Describe the format in words in title: the browser shows it in the hint:
<form>
<input name="zip" pattern="[0-9]{5}" title="Five digits" placeholder="ZIP code" required>
<button>Send</button>
</form>Length and numbers
minlength and maxlength limit the text length, and type="number" and date fields have min, max and step:
<input type="password" minlength="8" placeholder="At least 8 characters">
<input type="number" min="1" max="10" value="1">Phone
type="tel" has no built-in validation: numbers are written differently in different countries. But on a phone it opens the numeric keypad. If the format is known, add a pattern, for example \+[0-9]{11}.
Common mistake
pattern is set without required, expecting an empty field to fail. The pattern checks only the entered value: an empty field counts as valid, and the form is submitted. Another trap is pattern on a type="number" field: it has no effect there, numbers need min, max and step.
<form>
<input pattern="[0-9]{5}" placeholder="Leave me empty">
<button>Send</button>
</form>Functions used in this recipe
- pattern — A pattern (regular expression) the field value must match.
- type — The kind of an `<input>` field: from text and numbers to a date, colour and file.
- <input> — An input field; its kind is set by the `type` attribute.
- title — Extra information about an element; shown as a tooltip on mouse hover.
- :user-invalid — Matches an invalid field only after the user has interacted with it; `:user-valid` is the opposite.