The invalid Event
You'll learn how to detect and respond to validation failures in real time using the invalid event.
What is the invalid Event?
When a user tries to submit a form that contains fields violating their validation constraints (like required, pattern, min, or custom validity set with setCustomValidity()), the browser fires an invalid event on each field that failed validation. This happens before the form submission is blocked, giving you a chance to customize how validation errors are displayed or logged.
Think of it like a smoke detector: the moment something goes wrong (validation failure), the alarm sounds (the invalid event fires), alerting you to take action before the problem escalates (form submission proceeds).
How It Works
The invalid event fires on individual form controls, not on the form itself. You can listen for it using addEventListener:
const emailInput = document.querySelector('#email');
emailInput.addEventListener('invalid', (event) => {
console.log('Validation failed!');
console.log('Error:', event.target.validationMessage);
});
When a user tries to submit the form and this field doesn't meet its constraints, your listener runs. You can use this to create custom error messages, style the field differently, or track validation issues.
Preventing the Default Message
By default, the browser shows a tooltip with the validation error. You can prevent this and handle errors your own way:
emailInput.addEventListener('invalid', (event) => {
event.preventDefault();
// Show your own custom error message instead
});
Key Takeaway: The invalid event fires on form controls that fail validation during submission, letting you detect and customize validation feedback before the form is blocked.