Author
The Form Validation API allows JavaScript to programmatically validate HTML forms, leveraging HTML5 validation features while providing control over custom logic and messages.
It works with both form elements (<form>) and form controls (<input>, <textarea>, <select>).
validity – Returns a ValidityState object with Boolean flags:
valid → Overall validity (true if valid)valueMissing → Required field is emptytypeMismatch → Value doesn’t match input type (e.g., email)patternMismatch → Value doesn’t match patterntooLong / tooShort → Length issuesrangeUnderflow / rangeOverflow → Number/date out of boundsstepMismatch → Value doesn’t match step attributebadInput → Browser cannot convert the inputcustomError → Set via setCustomValidity()const input = document.getElementById("email");
if(input.validity.typeMismatch) {
console.log("Email is invalid!");
}
willValidate – true if the element can be validated.
validationMessage – Returns a localized message describing why the input is invalid.
console.log(input.validationMessage);
checkValidity() – Returns true if valid; otherwise false.
if(input.checkValidity()) console.log("Valid!");
reportValidity() – Checks validity and shows default browser error messages.
input.reportValidity();
setCustomValidity(message) – Sets a custom validation message; empty string clears the message.
input.setCustomValidity("Please enter a valid email!");
Form-level methods:
form.checkValidity() – Checks all elements in the formform.reportValidity() – Checks all elements and shows browser messagesform.reset() – Clears form values and validation states| Attribute | Description |
|---|---|
required | Field must be filled |
pattern | Regex pattern the input must match |
min / max | Min/max value for number/date inputs |
minlength / maxlength | Min/max string length |
type | Input type (email, url, number) |
step | Step interval for number/date inputs |
input – Fires when the value changes (real-time validation)invalid – Fires when a field fails validationsubmit – Fires when the form is submitted (use with checkValidity() or reportValidity())change – Fires when input loses focus and value changedconst input = document.getElementById("username");
input.addEventListener("invalid", (e) => {
console.log("Invalid field:", e.target.id);
});
Full Example
<form id="myForm">
<input id="username" type="text" placeholder="Username" required minlength="3">
<input id="email" type="email" placeholder="Email" required>
<input type="number" id="age" min="18" max="99" required>
<button type="submit">Submit</button>
</form>
<script>
const form = document.getElementById("myForm");
form.addEventListener("submit", (event) => {
event.preventDefault(); // Stop default submission
const username = document.getElementById("username");
const email = document.getElementById("email");
const age = document.getElementById("age");
// Custom validation
if(username.value.length < 3) username.setCustomValidity("Username must be at least 3 characters!");
else username.setCustomValidity("");
// Submit if valid, else show browser messages
if(form.checkValidity()) console.log("Form submitted successfully!");
else form.reportValidity();
});
// Real-time input validation
username.addEventListener("input", () => username.setCustomValidity(""));
email.addEventListener("input", () => email.setCustomValidity(""));
age.addEventListener("input", () => age.setCustomValidity(""));
</script>