What is the Constraint Validation API?

JavaScript

The short answer

The Constraint Validation API is a built-in browser API for validating form inputs. It provides methods and properties to check if an input's value meets its constraints (like required, minlength, pattern) and to show custom error messages. It works with HTML validation attributes and JavaScript, so you can validate forms without any external library.

HTML validation attributes

These attributes define the constraints:

<form>
<input type="email" required />
<input type="text" minlength="3" maxlength="50" />
<input type="number" min="1" max="100" />
<input
type="text"
pattern="[A-Za-z]+"
title="Letters only"
/>
</form>

The browser automatically validates these on form submission and shows default error messages.

JavaScript API

You can access validation programmatically:

const input = document.querySelector('input[type="email"]');
// Check if the input is valid
input.validity.valid; // true or false
// Specific validity states
input.validity.valueMissing; // true if required and empty
input.validity.typeMismatch; // true if not a valid email
input.validity.tooShort; // true if below minlength
input.validity.patternMismatch; // true if does not match pattern
// Get the validation message
input.validationMessage; // "Please fill out this field"
// Check validity and show browser tooltip
input.checkValidity(); // returns true/false, shows tooltip if invalid
input.reportValidity(); // same but always shows the tooltip

Custom error messages

const input = document.querySelector('#username');
input.addEventListener('input', () => {
if (input.validity.tooShort) {
input.setCustomValidity(
'Username must be at least 3 characters'
);
} else {
input.setCustomValidity(''); // clear custom error
}
});

setCustomValidity('') clears the error. If you set a non-empty string, the input is treated as invalid.

Preventing default validation UI

If you want to handle the validation UI yourself:

const form = document.querySelector('form');
form.addEventListener('submit', (event) => {
if (!form.checkValidity()) {
event.preventDefault();
// Show your own error messages
showCustomErrors(form);
}
});
// Prevent browser tooltips
form.setAttribute('novalidate', '');

novalidate disables the browser's built-in validation UI but the API still works. You can still call checkValidity() and read validity states.

Interview Tip

Show that you know the HTML attributes (required, pattern, minlength) and the JavaScript API (validity, checkValidity, setCustomValidity). The key point is that you can build form validation without any library using just the browser's built-in API.

Why interviewers ask this

Form validation is something every frontend developer does. Interviewers want to see if you know the native browser API before reaching for a library. Understanding the Constraint Validation API shows you know the web platform fundamentals.