CKTIS / HTML
oninvalid — handling failed validation
The oninvalid attribute contains JavaScript that handles the invalid event when a checked control fails form constraints. It does not automatically run on every keystroke.
Version: WHATWG HTML Living Standard; index snapshot date recorded separately
Syntax
oninvalid="JavaScript statements"oninvalid is the event-handler attribute for invalid. Its value is JavaScript code; inside the handler, event identifies the event and this identifies the element. The corresponding JavaScript property, element.oninvalid, accepts a function.
The event fires on a control eligible for validation when a check detects a constraint violation, such as an empty value with required. Checks can occur during form submission or through checkValidity() or reportValidity(). Typing alone does not fire this event.
invalid does not bubble: a form's oninvalid does not catch its controls' events. For shared handling, use addEventListener('invalid', handler, true). The event is cancelable: event.preventDefault() suppresses default problem reporting during interactive validation, but neither fixes the value nor allows an invalid form to be submitted. With checkValidity(), cancellation does not change the false result.
In the example, the first checkValidity() invokes the handler and returns false. After assigning OK, the second check returns true without another event.
Examples
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>oninvalid example</title>
<label>Required value <input id="field" required oninvalid="document.getElementById('result').textContent += event.type + '\n'"></label>
<pre id="result"></pre>
<script>
const field = document.getElementById('field');
const result = document.getElementById('result');
const first = field.checkValidity();
result.textContent += String(first) + '\n';
field.value = 'OK';
result.textContent += String(field.checkValidity());
</script>
</html>Result
invalid false true
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.