简体   繁体   中英

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?

您可以在正则表达式中为完全空白的文本添加另一个选项

<textarea pattern='(.{5,10}|^$)'></textarea>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM