Constraint Validation API Basics
Read validity state and custom messages with the Constraint Validation API.
Constraint Validation API Basics is a free HTML Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the HTML Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What Is the Constraint Validation API?
The Constraint Validation API is a JavaScript interface for reading and setting form validation state:
- Check if a field is valid
- Read which specific constraint failed
- Set custom error messages
- Trigger browser validation UI programmatically
validity Property
Every form control has a validity object with specific boolean flags:
const input = document.getElementById('email');
const v = input.validity;
console.log(v.valid); // true if all constraints pass
console.log(v.valueMissing); // true if required but empty
console.log(v.typeMismatch); // true if type doesn't match (e.g. bad email)
console.log(v.patternMismatch); // true if pattern fails
console.log(v.tooShort); // true if shorter than minlength
console.log(v.tooLong); // true if longer than maxlength
console.log(v.rangeUnderflow); // true if less than min
console.log(v.rangeOverflow); // true if more than maxcheckValidity Method
checkValidity() returns true/false and fires the invalid event:
const form = document.getElementById('my-form');
// Check entire form:
if (!form.checkValidity()) {
console.log('Form has errors');
}
// Check individual field:
const email = document.getElementById('email');
if (!email.checkValidity()) {
console.log('Email is invalid');
}
// The 'invalid' event fires on invalid fieldsreportValidity Method
reportValidity() shows the browser's native validation UI:
const input = document.getElementById('username');
// Shows native browser error tooltip if invalid:
const valid = input.reportValidity();
console.log(valid); // true or false
// On a form: validates all fields and shows first error:
document.getElementById('form').reportValidity();validationMessage Property
validationMessage returns the browser's error message string:
const email = document.querySelector('input[type=email]');
email.value = 'not-an-email';
console.log(email.validationMessage);
// e.g. "Please include an '@' in the email address..."
console.log(email.validity.typeMismatch); // truesetCustomValidity
setCustomValidity(message) sets a custom validation error:
const username = document.getElementById('username');
// Check availability on blur:
username.addEventListener('blur', async () => {
const res = await fetch(`/check-username?name=${username.value}`);
const { taken } = await res.json();
if (taken) {
username.setCustomValidity('This username is already taken.');
} else {
username.setCustomValidity(''); // empty string = clear the error
}
});Clearing Custom Validity
Must clear custom validity when the user fixes the issue:
const input = document.getElementById('username');
input.addEventListener('input', () => {
// Clear custom error when user starts typing again:
input.setCustomValidity('');
});
input.addEventListener('blur', async () => {
// Re-validate on blur:
const taken = await checkUsername(input.value);
input.setCustomValidity(taken ? 'Username taken' : '');
});invalid Event
The invalid event fires on form controls that fail validation:
document.querySelectorAll('input').forEach(input => {
input.addEventListener('invalid', (e) => {
e.preventDefault(); // prevent default browser tooltip
// Show your custom error UI instead:
showError(input, input.validationMessage);
});
});will-validate Property
willValidate is true if the element participates in constraint validation:
document.querySelectorAll(':input').forEach(el => {
if (el.willValidate) {
console.log(el.name, 'will be validated');
}
});
// Disabled, hidden, or output elements return willValidate = falseUsing Validity in Custom Validation
A complete custom validation example:
<form id="signup" novalidate>
<input type="email" id="email" name="email" required>
<span id="email-err" role="alert"></span>
<button type="submit">Sign Up</button>
</form>
<script>
const form = document.getElementById('signup');
const email = document.getElementById('email');
const err = document.getElementById('email-err');
form.addEventListener('submit', (e) => {
e.preventDefault();
err.textContent = '';
if (email.validity.valueMissing) {
err.textContent = 'Email is required.';
email.focus();
return;
}
if (email.validity.typeMismatch) {
err.textContent = 'Enter a valid email address.';
email.focus();
return;
}
// Submit...
});
</script>ValidityState Flags Summary
All ValidityState flags:
valueMissing— required but emptytypeMismatch— wrong type formatpatternMismatch— pattern regex failstooShort/tooLong— minlength/maxlengthrangeUnderflow/rangeOverflow— min/maxstepMismatch— not a valid step valuecustomError— setCustomValidity message setbadInput— browser cannot parse the value
Quick Check
How do you programmatically show the browser's native validation error popup?
Recap: Constraint Validation API
Constraint Validation API essentials:
input.validity— ValidityState object with specific flagscheckValidity()— returns true/false, fires invalid eventreportValidity()— checks + shows native error UIvalidationMessage— the browser's error stringsetCustomValidity(msg)— set custom error; empty string to clear
Frequently asked questions
Is the “Constraint Validation API Basics” lesson free?
Yes — the full text of “Constraint Validation API Basics” is free to read here on the web, and the HTML Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the HTML Academy course, upgrade to CoddyKit PRO.
What will I learn in “Constraint Validation API Basics”?
Read validity state and custom messages with the Constraint Validation API. You practise HTML Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start HTML Academy?
No prior experience is required. HTML Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Constraint Validation API Basics” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this HTML Academy lesson?
Yes. Every HTML Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- required pattern min max and maxlength
- The novalidate Attribute
- Constraint Validation API Basics
- HTML5 vs JavaScript Validation Trade-offs