Back to JavaScript Notes
Topic #398

Validation API

You will use the browser's built-in Constraint Validation API to check whether form fields satisfy HTML constraints and to show native validation messages.

What it is

The Validation API, more precisely the Constraint Validation API, is the browser's built-in system for validating HTML form controls. You declare constraints with attributes such as required, type="email", minlength, maxlength, pattern, min, max, and step. JavaScript can then ask whether a control or whole form is valid, show the browser's error UI, or add a custom error message.

The mental model is: HTML attributes define constraints, the browser evaluates them, and the API exposes the result. Related terms include validity states (element.validity), custom validity (setCustomValidity()), and reporting (reportValidity()).

Why it matters

  • It gives users immediate, accessible feedback without writing a full validation framework.
  • It works with native form submission, so invalid forms can be stopped before data is sent.
  • It reduces repetitive JavaScript for common rules like required fields, email format, and length limits.
  • It lets you combine browser rules with custom business rules using setCustomValidity().
  • It keeps validation messages consistent with the browser's built-in UI.

Syntax or steps

The smallest useful pattern is to call checkValidity() on a form or input. If it returns false, call reportValidity() to show the native message.

const input = document.querySelector('input');

if (!input.checkValidity()) {
  input.reportValidity();
}

For a whole form, use form.checkValidity() and form.reportValidity(). These methods return a boolean. checkValidity() only tests validity; reportValidity() tests validity and displays feedback.

Example

<form id="signup">
  <input name="email" type="email" required>
  <input name="password" type="password" minlength="8" required>
  <button type="submit">Create account</button>
</form>

<script>
const form = document.getElementById('signup');
const email = form.elements.email;
const password = form.elements.password;

form.addEventListener('submit', (event) => {
  if (!form.checkValidity()) {
    event.preventDefault();
    form.reportValidity();
    return;
  }

  console.log('Valid:', email.value, password.value);
});

password.addEventListener('input', () => {
  if (password.value.includes('123')) {
    password.setCustomValidity('Password must not contain 123.');
  } else {
    password.setCustomValidity('');
  }
});
</script>

Part by part:

  • The HTML attributes required, type="email", and minlength="8" create browser constraints.
  • form.checkValidity() returns false if any control fails a constraint.
  • event.preventDefault() stops submission while the form is invalid.
  • form.reportValidity() focuses the first invalid control and shows its native message.
  • password.setCustomValidity() adds a custom rule. Passing an empty string clears the custom error.

Common mistakes

  • Using checkValidity() and expecting an error message to appear. It only returns a boolean; use reportValidity() to show feedback.
  • Forgetting to clear custom validity. If you call setCustomValidity('error') and later do not call setCustomValidity(''), the field stays invalid.
  • Trusting client-side validation alone. The browser can be bypassed, so the server must validate again.
  • Calling reportValidity() on a control that is not part of a form or is not focusable. Native reporting works best with standard form controls.

When to use it

ApproachUse it whenKeep in mind
Constraint Validation APIYou need quick native checks for required fields, email format, length, range, or pattern.It is user feedback, not security.
Custom JavaScript validationYou need complex rules, cross-field checks, or a custom error UI.You must manage accessibility and message display yourself.
Server validationYou need to protect data and enforce business rules.Always required, even if the browser validates.

Use the Validation API for fast, accessible client-side feedback. Use custom JavaScript when the native UI or built-in constraints are not enough. Use server validation for trust.

Practice

Guided exercise: Create an input with required and type="email". Call input.checkValidity() when it is empty, then type a valid email and call it again.

Expected output: false for the empty field, then true for a valid email.

Challenge: Add a second password field named confirm. Use setCustomValidity() so it is invalid unless it matches the first password field.

Hint: On the input event, compare confirm.value with password.value. If they differ, set a custom message; if they match, set an empty string.

Quick check

Question: What is the difference between input.checkValidity() and input.reportValidity()?

Answer: Both return a boolean, but checkValidity() only tests validity, while reportValidity() also shows the browser's validation message and focuses the invalid control.

Summary

The Validation API lets JavaScript work with the browser's built-in form constraints instead of replacing them. Use checkValidity() to test, reportValidity() to show native feedback, and setCustomValidity() to add custom rules while still clearing them when the problem is fixed.

Want to go beyond the notes?

Join Coding Now Tech Institute's JavaScript course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

Validation API – FAQs

Quick answers about learning Validation API in JavaScript.

This free note from Coding Now Tech Institute explains Validation API in JavaScript — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every JavaScript topic on Coding Now Tech Institute, including Validation API, is 100% free with no signup required.
With focused practice, most students grasp Validation API in 1–3 days from these notes; pairing it with Coding Now Tech Institute's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the Coding Now Tech Institute Community (/community) — expert instructors answer within 24 hours.
Call NowEnroll Now