JavaScript: checkValidity()
The checkValidity() method checks whether a form or control satisfies its HTML validation constraints.
What you will learn
- How
required,type, and other constraints are checked - How to branch on the returned
trueorfalse - How to show an accessible error message near the related input
Minimal example
<form id="signup">
<label for="email">Email</label>
<input id="email" name="email" type="email" required>
<p id="message" aria-live="polite"></p>
<button type="button" id="check">Check</button>
</form>
<script>
const form = document.querySelector("#signup");
const message = document.querySelector("#message");
document.querySelector("#check").addEventListener("click", () => {
message.textContent = form.checkValidity()
? "The form is valid."
: "Please check the highlighted fields.";
});
</script>The method returns true when the constraints pass and false otherwise. It does not create your custom explanation, so provide text near the relevant control and do not rely on color alone.
Common constraints
requiredrejects an empty value.type="email"checks the value as an email-like address.min,max,minlength, andmaxlengthadd range or length rules.