Can I mark a field invalid from javascript?

css, html, javascript, validation

Solution

You could use the customValidity function for this purpose.

If you add a customValidity message to the field, it becomes invalid. When you set the message as an empty string, it becomes valid again (unless it is invalid because of other reasons).

`field.setCustomValidity("Invalid field.");` will make the field invalid.

`field.setCustomValidity("");` will make the field valid unless it fails an HTML5 constraint.

Problem

From reading this post I have found that there are some pseudo classes for 'valid' and 'invalid' input values introduced to HTML5. Is there a way I can mark an input field as invalid/valid from javascript? Or alternatively, can I override the validation method used?

Original source