The Web Forms API provides a set of properties and methods to handle form validation programmatically. While HTML5 attributes (like `required` and `type="email"`) handle basic validation, the Web Forms API allows you to customize error messages and create complex logic using JavaScript.
Enter a number between 100 and 300 to see the Web Forms API detect different validity states in real-time:
The checkValidity() method checks if an input element contains valid data. It returns true if the data is valid, and false otherwise.
const input = document.getElementById("myInput");
if (input.checkValidity()) {
console.log("Input is valid!");
} else {
console.log(input.validationMessage);
}
The validity property of an input element returns a ValidityState object. This object contains several boolean properties that tell you exactly *why* an input is invalid:
| Property | Returns True If... |
|---|---|
valueMissing |
A required field is empty |
rangeOverflow |
Value is greater than max attribute |
rangeUnderflow |
Value is less than min attribute |
typeMismatch |
Data doesn't match type (e.g. invalid email) |
valid |
The input data is completely valid |
You can override the browser's default error message using the setCustomValidity() method. This is perfect for multi-language support or branded error tones.
const pass = document.getElementById("password");
if (pass.value.length < 8) {
pass.setCustomValidity("Security rule: Password must be 8+ characters!");
} else {
pass.setCustomValidity(""); // Clear error to allow submittal
}
setCustomValidity() with a non-empty string, the form will never submit until you call it again with an empty string "".