0

HTML5 umbrella specs have the :invalid CSS pseudo-class for styling input with broken content.

My Firefox 38.2.1 doesn't send a form if one of the fields is invalid.

How can I -- in pure browser JS / DOM API -- get the field containing invalid data?

How can I do that check for the entire form?

0

2 Answers 2

2

You can get all invalid elements using querySelectorAll.

document.getElementById('test').onclick = function () {
    var invalid = document.querySelectorAll('input:invalid');
};

As you can see from the (simplistic) example above, I am doing this on the click event because the form won't submit if there are invalid elements.

The invalid variable contains a collection of invalid elements.

You can see a working example on JSFiddle.

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

2 Comments

Thanks! That really solution for my question. Some quick digging in DOM specs show me that there no direct functions/attributes on Node that answer the question but I may be wrong.
Yes, I was wrong. See comment of Traktor53 and answer of toskv. Now there are two proper answer and each may be useful depending on additional requirements. Thanks for all!
1

The HTMLFormElement object/type has an checkValidity method you can use to check that.

Check it here: https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement

4 Comments

Hm..., I follow links on w3.org/DOM/DOMTR and seems that DOM level 1/2/3/4 specs doesn't have HTMLFormElement.checkValidity Is that right that checkValidity an experimental feature?
@gavenkoa It's part of the HTML5 standard - see section 4.10.21.3 The constraint validation API for further information on checkValidity - and more
@Wolf, yes I meant the invalid event, I changed it to the method though, it makes more sense to use that. :)
@Traktor53 Wow! This is awesome! Your comment is really an answer to question!

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.