oninvalid Event
THE WORLD'S LARGEST WEB DEVELOPER SITE

oninvalid Event

❮ DOM Events ❮ Event Object

Example

Alert some text if an input field is invalid:

<input type="text" oninvalid="alert('You must fill out the form!');" required>
Try it Yourself »

More "Try it Yourself" examples below.


Definition and Usage

The oninvalid event occurs when a submittable <input> element is invalid.

For example, the input field is invalid if the required attribute is set and the field is empty (the required attribute specifies that the input field must be filled out before submitting the form).


Browser Support

The numbers in the table specify the first browser version that fully supports the event.

Event
oninvalid Yes 10.0 Yes Not supported Yes


Syntax

In HTML:

<element oninvalid="myScript">
Try it Yourself »

In JavaScript:

object.oninvalid = function(){myScript};
Try it Yourself »

In JavaScript, using the addEventListener() method:

object.addEventListener("invalid", myScript);
Try it Yourself »

Note: The addEventListener() method is not supported in Internet Explorer 8 and earlier versions.


Technical Details

Bubbles: No
Cancelable: Yes
Event type: Event
Supported HTML tags: <input>
DOM Version: Level 3 Events

More Examples

Example

Alert some text if an input field contains less than 6 characters:

Name: <input type="text" id="myInput" name="fname" pattern=".{6,}" required>

<script>
document.getElementById("myInput").addEventListener("invalid", myFunction);

function myFunction() {
    alert("Must contain 6 or more characters");
}
</script>
Try it Yourself »

Example

Alert some text if an input field contains a number that is less than 2 or greater than 5:

Number: <input type="number" id="myInput" name="quantity" min="2" max="5" required>

<script>
document.getElementById("myInput").addEventListener("invalid", myFunction);

function myFunction() {
    alert("You must pick a number between 2 and 5. You chose: " + this.value);
}
</script>
Try it Yourself »

Related Pages

JavaScript Tutorial: JavaScript Forms


❮ DOM Events ❮ Event Object