Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 669
Daniel Avatar asked Jun 23 '11 14:06

Daniel


People also ask

How do I bypass HTML5 validation?

To ignore HTML validation, you can remove the attribute on button click using JavaScript. Uer removeAttribute() to remove an attribute from each of the matched elements.

What does HTML5's pattern attribute do?

The pattern attribute specifies a regular expression the form control's value should match. If a non- null value doesn't conform to the constraints set by the pattern value, the ValidityState object's read-only patternMismatch property will be true.

Can you use regular expressions with HTML5 inputs?

Unlike the regular expression syntax used in programming languages, HTML5 does not require '^' and '$' to annotate the beginning and ending of values (it is assumed). Regular expressions can be enforced on inputs by using the “pattern” attribute.

Which are the correct input restrictions used for validation purposes in HTML5?

The value must be greater than or equal to the value. There must be a value (if set). Unless the step is set to the any literal, the value must be min + an integral multiple of the step. The number of characters (code points) must not be less than the value of the attribute, if non-empty.


2 Answers

Disclaimer:
All I am about to say here works for all modern browsers. The term "modern browser" in this context excludes IE9 and earlier. Also Safari for Windows has only partial support.

If all you need is a styling indicator, you can use pure CSS for this:

input[pattern]:invalid{
  color:red;
}

When using pattern, the onsubmit validation is automatically done by the browser (does not work in Safari for Windows).

like image 161
awe Avatar answered Sep 18 '22 13:09

awe


<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();}"/>
like image 20
Alex from Jitbit Avatar answered Sep 20 '22 13:09

Alex from Jitbit