Can I mark a field invalid from javascript?

Svish picture Svish · May 28, 2012 · Viewed 73.3k times · Source

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?

Answer

dajavax picture dajavax · Sep 19, 2013

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.