Événement oninvalid

Définition et utilisation

Un événement oninvalid se produit lorsque l'élément <input> est invalide.

Par exemple, si l'attribut required est configuré et que le champ est vide, le champ d'entrée est invalide (l'attribut required indique que le champ d'entrée doit être rempli avant de soumettre le formulaire).

Instance

Example 1

If the input field is invalid, prompt some text:

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

Essayez-le vous-même

More TIY examples are at the bottom of the page.

Syntax

In HTML:

<element oninvalid="myScript">

Essayez-le vous-même

In JavaScript:

object.oninvalid = function(){myScript};

Essayez-le vous-même

In JavaScript, use the addEventListener() method:

object.addEventListener("invalid", myScript);

Essayez-le vous-même

Note:Internet Explorer 8 or earlier versions do not support addEventListener() method.

Technical details

Bubble: Not supported
Cancelable: Support
Event type: Event
Supported HTML tags: <input>
DOM version: Level 3 Events

Browser support

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

Event Chrome IE Firefox Safari Opera
oninvalid Support 10.0 Support Support Support

More examples

Example 2

If the input field contains fewer than 6 characters, prompt some text:

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>

Essayez-le vous-même

Example 3

If the input field contains a number less than 2 or greater than 5, prompt some text:

Number: <input type="number" id="myInput" name="quantity" min="2" max="5" required>
<script>
document.getElementById("myInput").addEventListener("invalid", myFunction);
function myFunction() {
  alert("Vous devez choisir un nombre entre 2 et 5. Vous avez choisi: " + this.value);
}
</script>

Essayez-le vous-même

Pages associées

Tutoriel JavaScript : Formulaire JavaScript