Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 validation: field not required but, if filled in, must match pattern?

Playing around with HTML5 validation, it occurs to me that it is (seemingly) not possible to validate the input of a field unless it is required.

In other words, it's not possible to say "this field is not required, but if you do fill it in, it must match pattern X." For example:

<textarea pattern='.{5,10}'></textarea>

With 1-4 characters (inclusive) entered into the textarea, running element.willValidate and element.checkValidity() both return true.

I know HTML5 validation isn't perfect just yet. Is the "validate only if it's filled in" concept not possible with HTML5?

like image 402
Mitya Avatar asked Oct 31 '22 21:10

Mitya


1 Answers

You can add another option in regex for completely empty text

<textarea pattern='(.{5,10}|^$)'></textarea>
like image 191
programmerRaj Avatar answered Nov 09 '22 11:11

programmerRaj