What is the usage of oninvalid event in JavaScript?

The oninvalid event is triggered when a form field fails HTML5 validation constraints. It fires before form submission when an <input> field with validation attributes (like required, pattern, etc.) contains invalid data.

Syntax

element.oninvalid = function() {
    // Handle invalid input
};

// Or in HTML
<input oninvalid="handleInvalid()" />

Basic Example

Here's how to use oninvalid to show custom validation messages:

<!DOCTYPE html>
<html>
<body>
    <form>
        <label>Enter Name:</label>
        <input type="text" required 
               oninvalid="alert('Please enter your name before submitting!')">
        <br><br>
        
        <label>Enter Email:</label>
        <input type="email" required 
               oninvalid="alert('Please enter a valid email address!')">
        <br><br>
        
        <input type="submit" value="Submit">
    </form>
</body>
</html>

Custom Validation Messages

You can set custom validation messages using the setCustomValidity() method:

<!DOCTYPE html>
<html>
<body>
    <form>
        <label>Password (min 8 characters):</label>
        <input type="password" id="password" minlength="8" required 
               oninvalid="setCustomMessage(this)">
        <br><br>
        
        <input type="submit" value="Submit">
    </form>

    <script>
        function setCustomMessage(input) {
            if (input.validity.valueMissing) {
                input.setCustomValidity('Password is required!');
            } else if (input.validity.tooShort) {
                input.setCustomValidity('Password must be at least 8 characters long!');
            } else {
                input.setCustomValidity('');
            }
        }
    </script>
</body>
</html>

Common Use Cases

Validation Type Trigger Condition Example
Required Field Empty field with required <input required>
Email Format Invalid email with type="email" <input type="email">
Pattern Matching Value doesn't match pattern <input pattern="[0-9]{3}">
Length Constraints Value violates minlength/maxlength <input minlength="5">

Key Points

  • The oninvalid event only fires when HTML5 validation fails
  • It occurs before the form submission is blocked
  • Use setCustomValidity() to provide custom error messages
  • The event provides access to the validity object for detailed validation state

Conclusion

The oninvalid event provides a way to handle HTML5 form validation failures with custom messages. It's triggered when required fields are empty or input doesn't match validation constraints, allowing you to improve user experience with meaningful error feedback.

Updated on: 2026-03-15T23:18:59+05:30

331 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements