
invalid
16 March, 2023
0
0
0
Contributors
About
The invalid
event is triggered when a form element is invalid, either due to a constraint violation or a failed validation. This event is most commonly used with the HTMLInputElement
, HTMLSelectElement
, and HTMLTextAreaElement
types.
When an input element is invalid, its validity
property is updated to reflect the error. For example, if a required field is left blank, the valueMissing
property of the validity
object will be set to true
. Similarly, if the input value does not match a specified pattern, the patternMismatch
property will be set to true
.
Event listener
For example, suppose you have an <input>
element with the required
attribute:
<input type="text" id="myInput" required>
If the user tries to submit the form without entering a value in this field, the invalid
event will be triggered. You can attach an event listener to this event to handle the validation error, like this:
const inputElement = document.getElementById("myInput");
inputElement.addEventListener("invalid", function(event) {
event.preventDefault(); // Prevent form submission
// Code to handle validation error
});
Here, we're attaching an event listener to the invalid
event using the addEventListener()
method. When the event is triggered, the function inside the event listener will execute.
Inside the function, we're calling the preventDefault()
method on the event object to prevent the form from being submitted. We're also executing code to handle the validation error, such as displaying an error message to the user.
Property
Here's an example of using the oninvalid
property with a function assigned to it:
const element = document.getElementById("myInput");
element.oninvalid = function(event) {
event.preventDefault(); // Prevent the default validation behavior
console.log("Please enter a valid value!"); // Log a message to the console
};
Here, we retrieve the input element with the ID "myInput" using the getElementById
method. We then assign a function to the oninvalid
property of the element.
The function takes an event
parameter, which contains information about the invalid event. In this case, we use the preventDefault
method to prevent the default validation behaviour, which would display a validation message to the user. Instead, we log a message to the console indicating that the user should enter a valid value.
Inline
The invalid
event can be used inline by using the oninvalid
attribute. For example:
<input type="text" id="myInput" required oninvalid="alert('Please enter a value.');">
Here, we're using the oninvalid
attribute to attach an inline event handler to the invalid
event. When the field fails validation, the alert()
function will be executed, displaying a message to the user to enter a value.
While using inline event handlers can be convenient, it's generally not recommended for several reasons. Inline event handlers can make the HTML code harder to read and maintain, and they can also create potential security risks by allowing attackers to inject malicious code into your page.
Instead, it's recommended to use external JavaScript code to attach event listeners to DOM elements, as this allows you to separate the presentation and behaviour of your web page, making it easier to read, test, and maintain.
Programmatic trigger
You can trigger the invalid
event programmatically by calling the reportValidity()
method on a form element. The reportValidity()
method checks the validity of the form element and displays an error message if the element is invalid.
Here's an example:
const inputElement = document.getElementById("myInput");
if (!inputElement.checkValidity()) {
inputElement.reportValidity();
}
Here, we're using the getElementById()
method to get a reference to the <input>
element with an id
of myInput
. We're then calling the checkValidity()
method on this element to check whether it's valid. If the element is invalid, we're calling the reportValidity()
method to trigger the invalid
event and display an error message to the user.
Note that the reportValidity()
method is supported by most modern web browsers, but some older browsers may not support it. If you need to support older browsers, you can use a polyfill or fallback code to simulate the behaviour of the reportValidity()
method.
Warnings
The invalid
event is only triggered when the user tries to submit the form. If you want to perform real-time validation of form fields as the user types, you should use the input
event or other appropriate events for the type of input being validated.
It's important to note that the DOM can be changed dynamically by JavaScript or by the user, and that required
and pattern
attributes can be removed or disabled using DOM manipulation methods. If this happens, the invalid
event will not be triggered when the form is submitted, as the browser will not perform validation on the field that has been removed or disabled.
For example, suppose you have a required field like this:
<input type="text" id="myInput" required>
If the user or a script removes the required
attribute from this element or sets its disabled
property to true
, the field will no longer be required and the invalid
event won't be triggered when the form is submitted with an empty value.
To handle this situation, you can perform additional validation checks on the server-side or in JavaScript, or you can use the MutationObserver API to monitor changes to the DOM and take appropriate action when required fields are removed or disabled.
In general, it's a good practice to perform server-side validation of form data to ensure that all required fields are present and have valid values, as client-side validation can be bypassed or manipulated by savvy users or malicious scripts.
javascript
javascriptevent
invalid