Search code examples
javascriptvalidation

Reset individual form field's custom validity state


I have a basic form field that is valid in all conditions including when empty:

<input id="example1" name="example" type="text" />

In some unrelated (to this question) conditions I use JavaScript to mark this element as invalid:

id_('example1').setCustomValidity('All aboard the nope train!');
id_('example1').reportValidity();

I won't post the other code because it is perfectly valid if this form field is empty when the full form is submitted.

How do I reset the validity state of this specific form field without attempting to submit the entire form?

I have attempted id_('post_custom_selector').validity.valid = true; though it did not work and with all the methods for ValidityState being read-only I suspect that if I'm not missing anything else looking at the methods for the HTMLInputElement then I may be stuck having to duplicate the node and replace it.

Absolutely no frameworks or libraries.


Solution

  • If the first parameter for setCustomValidity is empty (it still must be set) then it will reset the validity of the element:

    id_('post_custom_selector').setCustomValidity('');