[英]html5 form validation - use pattern on optional field
I have an optional form field that I want to use the new html5 pattern option. 我有一个可选的表单字段,我想使用新的html5模式选项。 But, when I add the pattern, the field becomes required even though I do not have the required attribute.
但是,当我添加模式时,即使我没有required属性,该字段也成为必填字段。 I have included the pattern below.
我已包含以下模式。 I want the user to be able to leave the field blank, but if the user enters something in the field, then I want the pattern applied.
我希望用户能够将该字段留空,但是如果用户在该字段中输入内容,那么我希望应用该模式。 How would I accomplish this?
我将如何完成? Thanks in advance.
提前致谢。
pattern="[-a-zA-Z '.,]{3,50}"
The problem is that {3,50}
limiting quantifier requires at least 3 occurrences of the chars defined in the character class. 问题在于
{3,50}
限制量词至少需要出现3个在字符类中定义的字符。
You need to make the pattern optional. 您需要将模式设置为可选。 Wrap it with an optional non-capturing group:
用可选的非捕获组将其包装:
pattern="(?:[-a-zA-Z '.,]{3,50})?"
^^^ ^^
HTML5 patterns are wrapped with the anchors automatically, ie the pattern above will be translated into ^(?:(?:[-a-zA-Z '.,]{3,50})?)$
and will match HTML5模式自动用锚点包装,即上面的模式将转换为
^(?:(?:[-a-zA-Z '.,]{3,50})?)$
并匹配
^(?:
- start of the string ^(?:
-字符串开头 (?:[-a-zA-Z '.,]{3,50})?
- 1 or 0 occurrences of 3 to 50 hyphens, ASCII letters, spaces, '
, .
'
, .
or ,
,
)$
- end of string. )$
-字符串结尾。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.