HTML can check a form before it is sent, without any JavaScript. If a field is invalid, the browser stops the form and shows a message.
<form>
<p><label>Name <input type="text" name="name" required minlength="2"></label></p>
<p><label>Email <input type="email" name="email" required></label></p>
<p><label>Quantity <input type="number" name="qty" min="1" max="10" value="1"></label></p>
<p><label>Postcode <input type="text" name="zip" pattern="[0-9]{5}" title="Five digits"></label></p>
<button type="submit">Order</button>
</form>
Try submitting the form empty, or with a wrong postcode.
The attributes
| Attribute | Checks |
|---|---|
required | The field is not empty |
minlength, maxlength | The text length |
min, max, step | A number or date range |
pattern | The text matches a regular expression |
type | The format for email, url, number and so on |
Make errors clear
Use the title attribute to explain a pattern in plain words. Style valid and invalid fields with the CSS pseudo-classes :valid and :invalid.
Client-side checks are not security
Visitors and attackers can bypass anything in the browser. Always validate again on the server. HTML validation exists to help honest visitors fix mistakes quickly, not to protect your site.
Patterns that are too strict
Exercise: a sign-up form with checks
Build a form with a required name, a required email and a Subscribe button.
Show a possible solution
<form action="/subscribe" method="post">
<p><label>Name <input type="text" name="name" required></label></p>
<p><label>Email <input type="email" name="email" required></label></p>
<button type="submit">Subscribe</button>
</form>