如何在HTML5表单中查找哪个子元素无效

pab*_*abz 1 javascript validation html5 html5-validation

有没有一种使用html5自动表单验证来查找表单中哪些子元素无效的方法?

我知道我们可以通过调用checkValidity()方法逐个元素地检查。我正在寻找的是,如果有更短的方法。

例如,

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
}
Run Code Online (Sandbox Code Playgroud)

pab*_*abz 5

在MDN中找到了可以满足我要求的方法。但是我不确定这是否是最好的方法。

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;")
    }
}
Run Code Online (Sandbox Code Playgroud)