J

JavaScript Handbook

Clean • Professional

Web Form Validation API in JavaScript

2 minute

Web Form Validation API

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>).

Properties of Input Elements

validity – Returns a ValidityState object with Boolean flags:

  • valid → Overall validity (true if valid)
  • valueMissing → Required field is empty
  • typeMismatch → Value doesn’t match input type (e.g., email)
  • patternMismatch → Value doesn’t match pattern
  • tooLong / tooShort → Length issues
  • rangeUnderflow / rangeOverflow → Number/date out of bounds
  • stepMismatch → Value doesn’t match step attribute
  • badInput → Browser cannot convert the input
  • customError → Set via setCustomValidity()
const input = document.getElementById("email");
if(input.validity.typeMismatch) {
  console.log("Email is invalid!");
}

willValidatetrue if the element can be validated.

validationMessage – Returns a localized message describing why the input is invalid.

console.log(input.validationMessage);

Methods

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 form
  • form.reportValidity() – Checks all elements and shows browser messages
  • form.reset() – Clears form values and validation states

HTML5 Validation Attributes

AttributeDescription
requiredField must be filled
patternRegex pattern the input must match
min / maxMin/max value for number/date inputs
minlength / maxlengthMin/max string length
typeInput type (email, url, number)
stepStep interval for number/date inputs

Events Related to Form Validation

  • input – Fires when the value changes (real-time validation)
  • invalid – Fires when a field fails validation
  • submit – Fires when the form is submitted (use with checkValidity() or reportValidity())
  • change – Fires when input loses focus and value changed
const 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>

 

Article 0 of 0