Detect pseudo class :invalid from javascript

css, html, javascript, pseudo-class

Solution

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.

Problem

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?

Original source