12

Is there a way to detect the "appearance" of the pseudo-class :invalid on an input element through Javascript?

In other words, how could some Javascript code be triggered to run when the :invalid pseudo-class appears on an input element?

2
  • Maybe you can't use jQuery but have you try $('input').is(':invalid')? Commented Apr 4, 2013 at 13:33
  • Have you tried !input.validity.valid? Commented Apr 4, 2013 at 13:52

1 Answer 1

17

There is an invalid event that fires you can listen for.

The invalid event is fired when a submittable element has been checked and doesn't satisfy its constraints. The validity of submittable elements is checked before submitting their owner form, or after the checkValidity() of the element or its owner form is called.

https://developer.mozilla.org/en-US/docs/DOM/Mozilla_event_reference/invalid

There are also some properties you can access to check validity on elements, if that's more what you're after.

.validity.valid

The element meets all constraint validations, and is therefore considered to be valid.

https://developer.mozilla.org/en-US/docs/DOM/ValidityState

Edit: I have learned some things since I answered this question...

The .validity.valid is actually part of the constraint Constraint Validation API, and support for it is spotty at best, which is too bad (there is a lot of great stuff in that API).

However, something that appears to work well is querySelectorAll(':invalid'), which returns a non-live NodeList of all the form elements that are currently invalid. You could call addEventListener('change' ..etc, etc on your form elements, and query for validty whenever that fires.

Sign up to request clarification or add additional context in comments.

2 Comments

Using HTML where Markdown is available/more appropriate can lead to quirky post formatting. See stackoverflow.com/editing-help
@jldupont: It's a standard, and afaik every browser that has HTML5 validation enabled supports it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.