The checkValidity() Method
You'll learn how to programmatically check whether a form element or entire form passes all its validation rules.
So far you've learned how to set validation constraints (required, pattern, min, max, etc.) and inspect the validity object to see what's wrong with an individual field. But what if you want to trigger validation on demand — before the user clicks submit, or to check multiple fields at once?
What checkValidity() Does
The checkValidity() method is a built-in function you can call on any form element or on the <form> itself. It returns a boolean: true if all constraints are satisfied, false if any constraint fails.
When you call checkValidity() on:
- A single input: It checks only that field's constraints
- An entire form: It checks every form control inside
If validation fails, checkValidity() also fires an invalid event on the failing element(s), allowing you to display custom error messages.
Typical Use Cases
Check a single field:
const emailInput = document.querySelector('#email');
if (emailInput.checkValidity()) {
console.log('Email is valid!');
} else {
console.log('Email failed validation');
}
Check an entire form:
const form = document.querySelector('#myForm');
if (form.checkValidity()) {
console.log('All fields valid, safe to submit');
} else {
console.log('Some fields are invalid');
}
Think of checkValidity() as asking the browser: "Is this element okay to submit right now?" It's like a quality-check button you can press anytime.
Key Takeaway:
Use checkValidity() to programmatically verify whether a form element or entire form meets all validation constraints — it returns true if valid, false otherwise, and triggers invalid events on failures.