What is the Constraint Validation API?
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:
1<form>2 <input type="email" required />3 <input type="text" minlength="3" maxlength="50" />4 <input type="number" min="1" max="100" />5 <input6 type="text"7 pattern="[A-Za-z]+"8 title="Letters only"9 />10</form>
The browser automatically validates these on form submission and shows default error messages.
JavaScript API
You can access validation programmatically:
1const input = document.querySelector('input[type="email"]');23// Check if the input is valid4input.validity.valid; // true or false56// Specific validity states7input.validity.valueMissing; // true if required and empty8input.validity.typeMismatch; // true if not a valid email9input.validity.tooShort; // true if below minlength10input.validity.patternMismatch; // true if does not match pattern1112// Get the validation message13input.validationMessage; // "Please fill out this field"1415// Check validity and show browser tooltip16input.checkValidity(); // returns true/false, shows tooltip if invalid17input.reportValidity(); // same but always shows the tooltip
Custom error messages
1const input = document.querySelector('#username');23input.addEventListener('input', () => {4 if (input.validity.tooShort) {5 input.setCustomValidity(6 'Username must be at least 3 characters'7 );8 } else {9 input.setCustomValidity(''); // clear custom error10 }11});
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:
1const form = document.querySelector('form');23form.addEventListener('submit', (event) => {4 if (!form.checkValidity()) {5 event.preventDefault();6 // Show your own error messages7 showCustomErrors(form);8 }9});1011// Prevent browser tooltips12form.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.