HTML oninvalid Event Attribute
Description
The oninvalid
HTML event attribute specifies a script to be run 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 oninvalid
event attribute can be used to provide feedback to the user about why their input is invalid. For example, you could use it to display an error message or to prevent the user from submitting the form.
Here is an example of how to use the oninvalid
event attribute:
<input type="text" name="username" required oninvalid="alert('Please enter a username.')">
In this example, if the user tries to submit the form without entering a username, an alert message will be displayed.
Here is another example:
<input type="email" name="email" required oninvalid="this.classList.add('invalid');">
In this example, if the user tries to submit the form with an invalid email address, the input field will be given the invalid
CSS class. You can then use CSS to style the invalid input field in a way that is noticeable to the user.
The oninvalid
event attribute can be a useful tool for improving the user experience of your web forms. By providing feedback to the user about why their input is invalid, you can help them to correct their mistakes before submitting the form.
Syntax
<element oninvalid="script">
Values
- scriptThe name of the script to use when the event has been triggered.
Example
<!DOCTYPE html>
<html>
<head>
<title>oninvalid event</title>
</head>
<body>
<form action="#" method="get">
Click submit: <br>
<input type="text" oninvalid="testFunction()" name="info" required><br>
<input type="submit" value="Submit">
</form>
<script>
function testFunction() {
alert ("EXAMPLE: You did not fill out the required field!");
}
</script>
</body>
</html>
Browser Support
The following table will show you the current browser support for the HTML oninvalid
Event Attribute.
Desktop | |||||
Yes | Yes | Yes | Yes | Yes |
Tablets / Mobile | |||||
Yes | Yes | Yes | Yes | Yes | Yes |
Last updated by CSSPortal on: 14th October 2023