Before writing any validation code, use what the browser already provides.
Built-in validation attributes
<input type="email" required>
<input type="text" minlength="3" maxlength="20" pattern="[a-z0-9_]+" title="Lowercase letters, digits and underscores">
<input type="number" min="1" max="10" step="1">
<input type="url">
| Attribute | Checks |
|---|---|
required | not empty |
type="email", url, number… | the right format |
minlength, maxlength | text length |
min, max, step | number or date range |
pattern | a regular expression (the whole value must match) |
When a form is submitted, the browser checks all of them, blocks the submission and shows its own messages.
The Constraint Validation API
JavaScript can ask about the state of a field.
<input id="email" type="email" required value="not-an-email">
<script>
const input = document.querySelector("#email");
console.log(input.checkValidity()); // → false
console.log(input.validity.typeMismatch); // → true
console.log(input.validity.valueMissing); // → false
console.log(input.validationMessage.length > 0); // → true (the browser's own message)
</script>
validity flag | Meaning |
|---|---|
valueMissing | required but empty |
typeMismatch | wrong format for the type |
tooShort, tooLong | length rules |
rangeUnderflow, rangeOverflow | outside min / max |
patternMismatch | failed pattern |
customError | set with setCustomValidity |
valid | everything is fine |
Custom messages: setCustomValidity
<form id="f">
<input id="pw" type="password" minlength="8" placeholder="Password" required>
<button>Save</button>
</form>
<script>
const pw = document.querySelector("#pw");
pw.addEventListener("input", () => {
if (pw.validity.tooShort) {
pw.setCustomValidity("Please use at least 8 characters.");
} else {
pw.setCustomValidity(""); // an empty string means "valid"
}
});
</script>
Remember to clear the custom message with "", or the field stays invalid forever.
Checking the whole form
if (!form.checkValidity()) {
form.reportValidity(); // shows the browser's messages
}
Styling states in CSS
:valid, :invalid and :user-invalid let CSS style fields. See Form Validation Styles in the CSS course.
Turning the browser UI off
Add novalidate to the form if you want to show your own messages for every rule. The next lesson shows how: Custom Error Messages.