<input type="email" name="email" required>
<input type="number" name="age" min="18" max="120">
<input name="zip" pattern="[0-9]{5}" title="5 digits">
The browser checks rules that you declare in HTML, and it blocks the submit when one fails. You declare the rules with input types and attributes:
- types such as
email,url,numberanddate - attributes such as
required,min,max,minlength,maxlengthandpattern
These rules are called constraints. On submit, the browser checks them. If one fails, it blocks the submit and shows a message on the first invalid field. Typed inputs also give better mobile keyboards and pickers, like a number pad for number.
You can style fields with :invalid and :valid. :user-invalid waits until the user has interacted with the field. The Constraint Validation API lets you customise messages or add rules from JavaScript. It includes checkValidity(), reportValidity(), setCustomValidity() and the validity object. Add novalidate to the form to turn off the built-in messages.
You must still validate on the server, because client-side validation is only a convenience. Anyone can skip it with dev tools, or by sending requests to the server directly. So the server must check everything again.
- Input types and attributes declare the rules (constraints).
- On submit, the browser blocks an invalid form and shows a message.
- Style with
:invalidor:user-invalid, and customise with the Constraint Validation API. - Never trust the client: always validate again on the server.