admin管理员组

文章数量:1253959

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?

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?

Share Improve this question edited Apr 4, 2013 at 13:46 BoltClock 724k165 gold badges1.4k silver badges1.4k bronze badges asked Apr 4, 2013 at 13:29 jldupontjldupont 96.8k58 gold badges209 silver badges324 bronze badges 2
  • Maybe you can't use jQuery but have you try $('input').is(':invalid')? – ant_Ti Commented Apr 4, 2013 at 13:33
  • Have you tried !input.validity.valid? – Bergi Commented Apr 4, 2013 at 13:52
Add a ment  | 

1 Answer 1

Reset to default 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/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/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.

本文标签: htmlDetect pseudo class invalid from javascriptStack Overflow