Clean β’ Professional
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>Β