9

Is there a way to find which child elements in the form is invalid using the html5 automatic form validation?

I know we can check element by element, by calling checkValidity() method. What I'm seeking is, if there's a shorter way.

For example,

var contactForm = document.getElementById('contact-form');
if (contactForm.checkValidity() == false) {
    // something like contactForm.getInvalidChildren() and apply 
    // different style and error message based on the child type
}
TylerH
  • 20,799
  • 66
  • 75
  • 101
pabz
  • 534
  • 1
  • 5
  • 15

1 Answers1

24

I found this method in MDN which satisfies my requirement. But I'm not sure if it's the best way to do this.

var contactForm = document.getElementById('contact-form');
if (contactForm.checkValidity() == false) {
    var list = contactForm.querySelectorAll(':invalid');
    for (var item of list) {
        item.setAttribute("style", "background-color: red;")
    }
}
pabz
  • 534
  • 1
  • 5
  • 15
  • I found this to be a better selector (if you are not interested in selecting the form or fieldsets) `:invalid:not(form):not(fieldset)` – run_the_race Sep 12 '21 at 16:08