Course contentsShow
← Web Development
Lesson 902 of 2,98216. Forms and ValidationFree lesson

The Validity State Object

Accessing validation state through element.validity to check specific constraint failures.

The Validity State Object

You'll learn how to access detailed validation information for form inputs using the ValidityState object.

What is the Validity State?

When you add validation constraints to form inputs (like required, pattern, min, max), the browser doesn't just mark fields as valid or invalid — it tracks exactly which constraints are failing. The ValidityState object gives you this detailed breakdown.

Every form element has a .validity property that returns a ValidityState object with multiple boolean properties, each indicating whether a specific constraint has been violated.

The Core Properties

The ValidityState object includes properties like:

  • valid — true if all constraints pass
  • valueMissing — true if required is violated
  • typeMismatch — true if the input doesn't match its type (like invalid email)
  • patternMismatch — true if pattern fails
  • tooShort / tooLong — true if minlength / maxlength violated
  • rangeUnderflow / rangeOverflow — true if min / max violated
  • stepMismatch — true if step violated

Example Usage

const emailInput = document.querySelector('input[type="email"]');

emailInput.addEventListener('blur', () => {
  const validity = emailInput.validity;
  
  if (validity.valueMissing) {
    console.log('Email is required');
  } else if (validity.typeMismatch) {
    console.log('Please enter a valid email address');
  }
});

This lets you provide specific, helpful error messages instead of generic "this field is invalid" feedback.

Key Takeaway: The element.validity object gives you granular access to which validation constraints are failing, enabling precise user feedback for each type of validation error.