Every browser can validate a form without a line of JavaScript. The constraints live in the markup itself, and the browser refuses to submit until they are satisfied.
The constraints are things like required, type, pattern, min, and max. When one of them fails, the browser shows a message in the visitor's own language.
The previous lesson in this module covered "What Happens When a Form Is Submitted?", and this lesson is the last one in the HTML Forms module.
Which constraints does the browser enforce?
<input type="text" name="name" required>
<input type="email" name="email" required>
<input type="number" name="quantity" min="1" max="99" step="1">
<input type="text" name="code" pattern="[A-Z]{2}[0-9]{3}" required>
<input type="url" name="website" required>
<input type="text" name="username" minlength="3" maxlength="20">
<textarea name="bio" minlength="20" maxlength="500"></textarea>The rules depend on the type of the control.
An email field checks that the value looks like an address.
A number field is checked against the min, the max, and the step.
A url field needs a scheme.
The pattern attribute takes a regular expression, and it is anchored to the whole value. A pattern therefore has to describe the entire entry and not just part of it.
Two constraints deserve extra care.
The required attribute on a checkbox means that it has to be ticked, not merely present on the page.
And the step is a multiple of the base value. With the step="5", a value of 7 is invalid, while 10 and 15 are fine.
What does the visitor see when it fails?
The browser blocks the submission, focuses the offending field, and shows a message.
The exact wording and the position depend on the browser, which is the reason you should never depend on the precise text.
The behaviour itself, meaning no navigation, a focused field, and an explanation, is consistent everywhere.
type="email" with the value "not-an-email"
-> the browser refuses to submit and reports that the value is not an email address
type="number" with the value "12" and max="10"
-> the value must be less than or equal to 10
pattern="[A-Z]{2}[0-9]{3}" with the value "ab123"
-> the value must match the requested formatValidation on the client is a convenience and not a security measure. Anybody can bypass it, so the server has to check every value again.
What the client-side check buys you is fewer round trips and a faster correction for people who make a typo.
Can you write your own messages?
You can, and it is worth doing when the default message is vague.
The setCustomValidity() method attaches a message to a control, and the browser shows it instead of the default one.
const code = document.querySelector('#code');
code.addEventListener('input', () => {
code.setCustomValidity('');
const value = code.value.trim();
if (value && !/^[A-Z]{2}[0-9]{3}$/.test(value)) {
code.setCustomValidity('Use two capital letters followed by three digits, like AB123.');
}
});Two rules make this work.
You clear the custom message first, on every input, or it sticks around after the visitor fixes the value.
And you call the reportValidity() on the form to display it immediately, because setting the message alone does not show it until the next validation attempt.
How do you show which field is wrong?
The browser exposes the validity state of each control, so the CSS can react to it.
The :user-invalid pseudo-class applies only after the visitor has interacted with the field. That avoids the insulting effect of a red box that appears on an untouched form.
input:user-invalid {
border-color: #b3261e;
}
input:user-valid {
border-color: #2e7d32;
}
.field-error {
color: #b3261e;
font-size: 0.875rem;
}There are two cautions here.
The :invalid pseudo-class matches a field that is empty and untouched, so styling it directly turns every new form red before the visitor has typed anything. The :user-invalid class avoids that.
And a red border on its own is not enough. Colour alone excludes anybody who cannot tell red from green, so pair it with a message or an icon.
Why does the server have to validate too?
Because client-side validation is a suggestion and not a gate.
The rules live in the page that the visitor downloaded, and that page is not the copy that the server checks. Anybody can submit a request without loading the form at all, using a script or the developer tools of the browser.
what the browser checks what the server must check
-------------------------------- --------------------------------
the value looks like an email the address exists and can receive mail
the number is in range the number is in range
the pattern matches the pattern matches
the field is not empty the field is not emptyThe two layers do different jobs.
The client-side check is a kindness. It tells the visitor about a typo immediately, and it does it without a round trip.
The server-side check is the authority. It is the only one that cannot be bypassed.
A good rule is to treat the validation of the browser as a first draft, and to write the real one on the server with the same constraints and the same messages.
How do you turn the built-in validation off?
The novalidate attribute on the form suppresses the automatic checking of the browser. That is what you do when you are building your own validation with your own messages.
The formnovalidate attribute does the same for a single button, and that is how you offer a "save without validating" action next to a strict one.
<form action="/draft" method="post" novalidate>
...
<button type="submit" formnovalidate>Save draft</button>
<button type="submit">Publish</button>
</form>Use it sparingly.
The messages of the browser are already localised, already accessible, and already familiar to the visitor.
Replacing them with your own means implementing the whole experience. You show the error, you move the focus to the field, you describe what is wrong in the text, and you do it in every language that your visitors use.
Which values does the browser consider empty?
There is one detail that catches people out. A field that contains only spaces counts as filled for the required attribute.
The browser does not trim your input before it checks it.
<input type="text" name="name" required>Submit a field with a single space in it and the browser will accept it.
If spaces are not valid input, strip them yourself before you validate. Do it on the server, where it cannot be bypassed, and do it in the browser as well if you want the feedback to be immediate.
Quick reference
- The constraints live in the markup. There is required, type, pattern, min, max, step, and minlength.
- A pattern has to match the whole value, so you anchor it.
- Client-side validation is a convenience, and the server has to validate again.
- The
setCustomValidity('')call clears a custom message, and you do it on every input. - You use the
:user-invalidclass and not the:invalidclass, to avoid marking untouched fields as wrong. - You never rely on colour alone to signal an error.
Try it yourself: you build a form with an email, a number with a range, and a pattern field. Then you try to submit it empty.
You note which field the browser focuses. Now you add a custom message for the pattern field, and you check that it appears and that it disappears once the value is corrected.