The HTML oninvalid event
The HTML oninvalid attribute runs JavaScript when a submittable control fails constraint validation. It is an inline handler for the invalid event; in modern code prefer addEventListener('invalid', …).
Overview
The oninvalid event attribute runs JavaScript when a form control fails validation. In JavaScript the event itself is named invalid — drop the on prefix when you call addEventListener.
It is a form-related event, fired by form controls such as <input>, <select> and <textarea> (or the <form> itself) as the user interacts with them and as data is submitted or validated.
You can wire this up with the inline oninvalid HTML attribute, but the modern, recommended approach is element.addEventListener('invalid', handler) in JavaScript. That keeps behavior out of your markup, lets you attach several handlers to the same event, and makes them easy to remove. The inline attribute is fine for quick demos.
Syntax
<element oninvalid="handler()">…</element>
element.addEventListener('invalid', handler);
Best practices
- Prefer
element.addEventListener('invalid', handler)over the inlineoninvalidattribute — it separates behavior from markup and allows multiple handlers. - Use native form validation (
required,type,pattern) alongside JavaScript, not instead of it. - Re-validate on the server too — client-side events can be bypassed.
- Give every control a <label> so the interaction is accessible.
Frequently asked questions
What is the oninvalid event?
invalid.What is the difference between oninput and onchange?
Should I rely on form events for validation?
Should I use the oninvalid attribute or addEventListener?
addEventListener('invalid', …) in JavaScript. The inline oninvalid attribute works but mixes behavior into the markup and allows only one handler per element.