The JavaScript Validation API provides built-in browser validation for HTML forms without needing complex JavaScript. It helps validate user input before submission and provides user-friendly error messages.
checkValidity() MethodChecks if an input element's value is valid according to its constraints.
setCustomValidity() MethodSets a custom validation message for the input element.
| Property | Description | Type |
|----------|-------------|------|
| validationMessage | Returns the error message that would be displayed | string |
| validity | Returns a ValidityState object containing validation properties | object |
| willValidate | Indicates whether the element will be validated | boolean |
| checkValidity() | Returns true if element's value has no validity problems | method |
| reportValidity() | Reports invalid field to user (shows validation message) | method |
| setCustomValidity(message) | Sets a custom validation message | method |
The validity property returns a ValidityState object with these boolean properties:
| Property | Description | Triggered When |
|----------|-------------|----------------|
| valueMissing | Value is missing but required | required attribute present but empty |
| typeMismatch | Value doesn't match expected type | Email/URL format incorrect |
| patternMismatch | Value doesn't match pattern | pattern regex doesn't match |
| tooLong | Value exceeds maxLength | Input longer than maxlength |
| tooShort | Value is shorter than minLength | Input shorter than minlength |
| rangeUnderflow | Value is less than min | Number below min attribute |
| rangeOverflow | Value is greater than max | Number above max attribute |
| stepMismatch | Value doesn't fit step rules | Doesn't match step increment |
| badInput | Browser can't convert value | Invalid numeric input |
| customError | Custom validity set | setCustomValidity() used |
| valid | All validity constraints are satisfied | All checks pass |
rangeUnderflow Property ExamplerangeOverflow Property ExamplecheckValidity() - Quick way to check if an input is validsetCustomValidity() - Set custom validation messagesrangeUnderflow - Triggered when value is below minimumrangeOverflow - Triggered when value is above maximumnovalidate on form to disable browser default validation and use customreportValidity() to show validation messages to usersThe JavaScript Validation API provides a powerful, built-in way to validate forms with minimal code, while still allowing for complex custom validation when needed.