HTML5, how to force input pattern validation on value change?

Viewed 45345

I am trying to learn HTML5 and came across the following. I would like to use the pattern input keyword to validate the input as the user types it (e.g. validation after pressing tab or changing focus from input box).

I have tried the following:

<input name="variable" value="" tabindex="1" maxlength="13" required="required" pattern="${expectedValue}" onchange="this.variable.validate()" />  </li>

And as well:

<input name="variable" value="" tabindex="1" maxlength="13" required="required" pattern="${expectedValue}" />  </li>

I made up the code for

onchange="this.variable.validate()" 

How to trigger the validation on value change? I am able to do this only onSubmit.

8 Answers
<input type="text" name="country" pattern="[A-z]{3}" oninput="this.reportValidity()" />

Check the oninput bit.

You might want to check older browsers though, something like:

<input type="text" name="country" pattern="[A-z]{3}"
    oninput="if (typeof this.reportValidity === 'function') {this.reportValidity();}"/>

My suggestion is to prevent the user from entering invalid characters into an input in the first place, so they don't have to go back and correct the form.

<label for="test">Only accepts 'a' characters</label>
<input id="test" type="text"
  placeholder="aa" pattern="[a]{1,2}" maxlength="2"
  oninput="if (!this.checkValidity()) this.value = this.value.slice(0, -1)" /> 

Related