简体   繁体   English

HTML5 验证:字段不是必需的,但如果填写,必须匹配模式?

[英]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.在玩 HTML5 验证时,我突然想到,除非需要,否则(似乎)不可能验证字段的输入。

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."换句话说,它不是可以说“不需要此领域,但如果填它,它必须格局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.在 textarea 中输入 1-4 个字符(包括)后,运行element.willValidateelement.checkValidity()都返回 true。

I know HTML5 validation isn't perfect just yet.我知道 HTML5 验证还不完美。 Is the "validate only if it's filled in" concept not possible with HTML5? HTML5 无法实现“仅在填充时才进行验证”的概念吗?

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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