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.
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).
The numbers in the table specify the first browser version that fully supports the event.
Event | |||||
---|---|---|---|---|---|
oninvalid | Yes | 10.0 | Yes | Yes | Yes |
In JavaScript, using the addEventListener() method:
object.addEventListener("invalid",
myScript);
Try it Yourself »
Bubbles: | No |
---|---|
Cancelable: | Yes |
Event type: | Event |
HTML tags: | <input> |
DOM Version: | Level 3 Events |
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 »
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 »
JavaScript Tutorial: JavaScript Forms
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!