Events
oninvalid
A control fails constraint validation during a validation attempt. HTML event-handler content attribute or corresponding event-handler property; the event fires only on relevant targets. The example uses document.getElementById("field"). Event interface: Event. For the described native event: bubbles: no; cancelable: yes. Listen directly or capture on the form; canceling can suppress native validation UI but does not make the control valid. Example: Try submitting the empty required field. The event listener is registered with addEventListener(), which avoids inline script handlers and supports multiple listeners. Inline handlers require a CSP that permits them; do not insert untrusted code into handler attributes.
Formal Syntax & Structure
html syntaxhtml
<input oninvalid="handleEvent(event)">target.addEventListener("invalid", event => { /* handle event */ });Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| oninvalid | JavaScript handler body | Optional HTML event-handler code; the example uses a registered listener instead. Not a Boolean attribute. |
| event | Event | Event object delivered to the addEventListener callback; event.type is "invalid". Inspect target, currentTarget, bubbles and cancelable as appropriate. |
Working Example
Example Snippethtml
<form id="form"> <label for="field">Name</label> <input id="field" name="name" required> <button>Submit</button> <button type="reset">Reset</button></form><p role="status" id="log">Waiting for invalid</p><script> const target = document.getElementById("field"); const log = document.getElementById("log"); target.addEventListener("invalid", event => { log.textContent = String(event.type); }); document.getElementById("form").addEventListener("submit", event => event.preventDefault());</script>