artfulrobot
artfulrobot

Reputation: 21397

How to reset inbuilt HTML input validity

In Firefox, at least, native HTML5 input element validity, e.g. a required text field, shows up as a red border, but only after interaction.

e.g. in the example below, I initially see two input boxes. If I type something in one of them, delete it and press Tab, the first one now glows red to show me it's invalid (because it's required).

Using Javascript, how can I reset the form to the pristine initial state, where the red border is not showing?

<form action='#'>
  <div>
    <input required name="a" type="text"   />
    <input required name="b" />
  </div>
</form>

Upvotes: 2

Views: 919

Answers (1)

SimonR
SimonR

Reputation: 1268

The only reliable way I've found is to reset the form, either via a <button type="reset"> or through form.reset().

Note, however, that this will wipe the values of any and all fields in the form, so if you need these to remain you'll need to repopulate their values after the reset is done.

Setting <form novalidate> will work, however subsequently removing the novalidate attribute will make the field(s) show errors again.

Upvotes: 2

Related Questions