HTML oninvalid Attribute

Beginner
⏱️ 6 min read
📚 Updated: Jun 2026
🎯 3 Examples
Events & Handlers

Introduction

The oninvalid attribute is an inline event handler that runs JavaScript when the invalid event fires — when a form control fails HTML5 constraint validation. That happens when a field breaks rules like required, min, max, pattern, or type="email", usually when the user tries to submit the form. Use it with setCustomValidity() to show friendly error messages, and clear custom validity on oninput so the field can become valid again. Prefer visible inline errors over alert(). Pair with novalidate on the form only if you replace browser validation entirely.

What You’ll Learn

01

Event handler

Inline JS.

02

invalid event

Validation fail.

03

required, pattern

Constraints.

04

setCustomValidity

Custom message.

05

addEventListener

Preferred way.

06

Inline errors

Accessible UX.

Purpose of oninvalid Attribute

The primary purpose of oninvalid is to respond when a form field does not meet its validation constraints. Instead of a generic browser tooltip, you can set a clear message with setCustomValidity(), highlight the field, or reveal an error paragraph. This makes validation feedback easier to understand — especially for beginners filling out a form for the first time.

The browser runs validation when the user submits a form (unless novalidate is set). If any control is invalid, submission is blocked and the invalid event fires on each invalid field. Your handler runs at that moment — a good place to customize the message or update the UI.

💡
Clear custom validity on input

After setCustomValidity("Error message"), reset with setCustomValidity("") in an oninput handler. Otherwise the field stays invalid even after the user fixes it.

📝 Syntax

Set oninvalid on a validatable form control:

oninvalid.html
<input type="text" id="username" required
  oninvalid="setUsernameError()"
  oninput="this.setCustomValidity('')">

<script>
  function setUsernameError() {
    document.getElementById("username").setCustomValidity(
      "Username is required."
    );
  }
</script>

Syntax Rules

  • Value is JavaScript executed when the invalid event fires.
  • Works on validatable elements: input, textarea, select.
  • Typically fires on form submit when a constraint fails (not on every keystroke).
  • Use setCustomValidity(message) for custom text; clear with setCustomValidity("").
  • JavaScript: element.oninvalid = function() { … }.
  • Modern alternative: element.addEventListener("invalid", handler).
  • The invalid event does not bubble in all cases the same way — attach to each field or use capture on the form.

💎 Values

The oninvalid attribute accepts a string of JavaScript code:

  • oninvalid="showError(this)" — Pass the invalid element.
  • oninvalid="this.setCustomValidity('Required')" — Inline custom message.
  • JavaScript: field.oninvalid = () => { … } assigns the handler.
oninvalid-js.html
const email = document.getElementById("email");

email.addEventListener("invalid", () => {
  email.setCustomValidity("Please enter a valid email address.");
});

email.addEventListener("input", () => {
  email.setCustomValidity("");
});

⚡ Quick Reference

Actioninvalid fires?Notes
Submit with empty required fieldYesMost common trigger
Email field with bad formatYestype="email" constraint
checkValidity() returns falseYesProgrammatic check
User types to fix the valueNoUse oninput to clear errors
Form has novalidateNoBrowser validation disabled
Handler attributeoninvalidInline on element

Applicable Elements

TargetSupported?Notes
<input required>YesEmpty value on submit
<input type="email">YesFormat validation
<input pattern="...">YesRegex constraint
<textarea required>YesMulti-line required
<select required>YesNo option selected
<button> (no constraints)NoNot a validated value field

oninvalid vs oninput vs reportValidity()

API / handlerWhen it runsTypical use
oninvalidConstraint check failsCustom error message on submit
oninputEvery value changeClear setCustomValidity
checkValidity()Called in JSTest validity without UI
reportValidity()Called in JSShow native error bubble

Examples Gallery

Required field custom message, addEventListener, and pattern validation with inline errors.

👀 Live Preview

Submit with an empty required field — a custom message appears:

Example — Required username

Set a custom message when a required field is empty on submit:

required-oninvalid.html
<form>
  <label for="username">Username:</label>
  <input type="text" id="username" required
    oninvalid="this.setCustomValidity('Username is required.')"
    oninput="this.setCustomValidity('')">
  <input type="submit" value="Submit">
</form>
Try It Yourself

How It Works

The browser blocks submit and fires invalid on the empty required input. Custom validity sets your message; oninput clears it when the user types.

Dynamic Values with JavaScript

Attach the handler with addEventListener:

dynamic-oninvalid.html
<input type="text" id="dynamicField" required>

<script>
  const field = document.getElementById("dynamicField");

  field.addEventListener("invalid", function () {
    field.setCustomValidity("This field is invalid. Please provide a valid input.");
  });

  field.addEventListener("input", function () {
    field.setCustomValidity("");
  });
</script>
Try It Yourself

How It Works

Register listeners once at page load. Submit or reportValidity() triggers validation and your custom message.

Example — Pattern validation

Enforce a password rule with pattern and a friendly oninvalid message:

pattern-oninvalid.html
<input type="password" id="pwd"
  pattern=".{8,}" required
  oninvalid="this.setCustomValidity('Password must be at least 8 characters.')"
  oninput="this.setCustomValidity('')">
Try It Yourself

How It Works

HTML constraints do the checking; your handler only improves the error message the user sees.

♿ Accessibility

  • Use inline errors, not alert() — Blocking dialogs are hard for screen reader and keyboard users.
  • Link errors with aria-describedby — Point the input at the error message element id.
  • Use aria-invalid="true" — Set when invalid; remove when the field passes validation.
  • Associate labels — Every validated field needs a visible <label>.
  • Don’t rely on color alone — Show error text, not only a red border.

🧠 How oninvalid Works

1

User submits form

Click Submit button.

Submit
2

Browser checks constraints

required, pattern, etc.

Validate
3

invalid fires

oninvalid runs.

Event
=

Clear feedback

Custom message, no submit.

Browser Support

The invalid event and oninvalid handler work wherever HTML5 constraint validation is supported — Chrome, Firefox, Safari, Edge, and IE 10+.

DOM Events · Fully supported

Universal oninvalid support

All major browsers fire invalid on form controls that fail constraint validation.

98% Browser support
Google Chrome Fully supported
Full support
Mozilla Firefox Fully supported
Full support
Apple Safari Fully supported
Full support
Microsoft Edge Fully supported
Full support
Internet Explorer IE 10+ supported
Full support
Opera Fully supported
Full support
oninvalid attribute 98% supported

Bottom line: Use with HTML5 constraints and setCustomValidity for accessible client-side validation.

💡 Best Practices

✅ Do

  • Use setCustomValidity() for clear, friendly messages
  • Clear custom validity on input when the user fixes the field
  • Show inline errors with aria-describedby and aria-invalid
  • Prefer addEventListener("invalid", …) in production
  • Combine HTML constraints (required, pattern) with custom messages

❌ Don’t

  • Use alert() in oninvalid — blocks the user
  • Forget to reset setCustomValidity("") after the user types
  • Rely on client validation alone — always validate on the server too
  • Set novalidate unless you implement full custom validation
  • Attach oninvalid to elements without validation constraints

Conclusion

The oninvalid attribute runs JavaScript when a form control fails HTML5 validation — the right hook for custom error messages and accessible inline feedback.

Use setCustomValidity, clear it on input, and prefer addEventListener("invalid", …) over blocking alerts.

Key Takeaways

Knowledge Unlocked

Five truths every developer should know about oninvalid

Bookmark these before building validated forms.

5
Core concepts
📝 02

Form fields

input, select.

Scope
💬 03

setCustomValidity

Your message.

API
🔄 04

Clear on input

Reset validity.

Pattern
05

Inline errors

Not alert().

A11y

❓ Frequently Asked Questions

It runs JavaScript when the invalid event fires — when a form control fails HTML5 constraint validation.
input, textarea, and select with validation constraints like required, pattern, or type="email".
Call setCustomValidity("Your message") in the handler and clear it with setCustomValidity("") on input.
On form submit when a field fails validation, or when checkValidity() / reportValidity() is called.
addEventListener("invalid", handler) is preferred for production. Inline oninvalid works for learning.
Yes in all modern browsers with HTML5 validation; Internet Explorer 10+.

Master form validation feedback

Practice the oninvalid attribute with required-field and pattern examples in the Try It editor.

Try oninvalid demo →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful