Constraint Validation API Basics
Read validity state and custom messages with the Constraint Validation API.
What Is the Constraint Validation API?
The Constraint Validation API is a JavaScript interface for reading and setting form validation state:
- Check if a field is valid
- Read which specific constraint failed
- Set custom error messages
- Trigger browser validation UI programmatically
validity Property
Every form control has a validity object with specific boolean flags:
const input = document.getElementById('email');
const v = input.validity;
console.log(v.valid); // true if all constraints pass
console.log(v.valueMissing); // true if required but empty
console.log(v.typeMismatch); // true if type doesn't match (e.g. bad email)
console.log(v.patternMismatch); // true if pattern fails
console.log(v.tooShort); // true if shorter than minlength
console.log(v.tooLong); // true if longer than maxlength
console.log(v.rangeUnderflow); // true if less than min
console.log(v.rangeOverflow); // true if more than maxAll lessons in this course
- required pattern min max and maxlength
- The novalidate Attribute
- Constraint Validation API Basics
- HTML5 vs JavaScript Validation Trade-offs