模式属性值不是有效的正则表达式 [英] Pattern attribute value is not a valid regular expression

查看:148
本文介绍了模式属性值不是有效的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的HTML具有以下输入元素(旨在接受以".com"结尾的电子邮件地址):

My HTML has the following input element (it is intended to accept email addresses that end in ".com"):

<input type="email" name="p_email_ad" id="p_email_ad" value="" required="required" pattern="[\-a-zA-Z0-9~!$%\^&amp;*_=+}{\'?]+(\.[\-a-zA-Z0-9~!$%\^&amp;*_=+}{\'?]+)*@([a-zA-Z0-9_][\-a-zA-Z0-9_]*(\.[\-a-zA-Z0-9_]+)*\.([cC][oO][mM]))(:[0-9]{1,5})?$" maxlength="64">

在过去两个月中的某个时候,Chrome在验证该输入时已开始返回以下JavaScript错误(并防止提交父表单):

At some point in the past 2 months, Chrome has started returning the following JavaScript error (and preventing submission of the parent form) when validating that input:

模式属性值 [\-a-zA-Z0-9~!$%\^&*_=+}{\'?]+(\.[\-a-zA-Z0-9~!$%\^&*_=+}{\'?]+)*@([a-zA-Z0-9_][\-a-zA-Z0-9_]*(\.[\-a-zA-Z0-9_]+)*\.([cC][oO][mM]))(:[0-9]{1,5})?$ 不是有效的正则表达式:未捕获的SyntaxError:无效 正则表达式: /[\-a-zA-Z0-9~!$%\^&*_=+}{\'?]+(\.[\-a-zA-Z0-9~!$%\^&*_=+}{\'?]+)*@([a-zA-Z0-9_][\-a-zA-Z0-9_]*(\.[\-a-zA-Z0-9_]+)*\.([cC][oO][mM]))(:[0-9]{1,5})?$/:无效的转义

Pattern attribute value [\-a-zA-Z0-9~!$%\^&*_=+}{\'?]+(\.[\-a-zA-Z0-9~!$%\^&*_=+}{\'?]+)*@([a-zA-Z0-9_][\-a-zA-Z0-9_]*(\.[\-a-zA-Z0-9_]+)*\.([cC][oO][mM]))(:[0-9]{1,5})?$ is not a valid regular expression: Uncaught SyntaxError: Invalid regular expression: /[\-a-zA-Z0-9~!$%\^&*_=+}{\'?]+(\.[\-a-zA-Z0-9~!$%\^&*_=+}{\'?]+)*@([a-zA-Z0-9_][\-a-zA-Z0-9_]*(\.[\-a-zA-Z0-9_]+)*\.([cC][oO][mM]))(:[0-9]{1,5})?$/: Invalid escape

Regex101.com 喜欢regex模式,但Chrome浏览器不喜欢.我的语法有误吗?

Regex101.com likes the regex pattern, but Chrome doesn't. What syntax do I have wrong?

推荐答案

使用

pattern="[-a-zA-Z0-9~!$%^&amp;*_=+}{'?]+(\.[-a-zA-Z0-9~!$%^&amp;*_=+}{'?]+)*@([a-zA-Z0-9_][-a-zA-Z0-9_]*(\.[-a-zA-Z0-9_]+)*\.([cC][oO][mM]))(:[0-9]{1,5})?"

问题是某些不应该转义的字符被转义了,例如字符类中的'^.请注意,字符类中的-可以转义,但不必在其开始时进行转义.

The problem is that some chars that should not be escaped were escaped, like ' and ^ inside the character classes. Note that - inside a character class may be escaped, but does not have to when it is at its start.

还要注意,HTML5引擎将整个模式包装在^(?:)$构造中,因此不需要在模式末尾使用$字符串锚定结尾.

Note also that HTML5 engines wraps the whole pattern inside ^(?: and )$ constructs, so there is no need using $ end of string anchor at the end of the pattern.

测试:

<form>
   <input type="email" name="p_email_ad" id="p_email_ad" value="" required="required" pattern="[-a-zA-Z0-9~!$%^&amp;*_=+}{'?]+(\.[-a-zA-Z0-9~!$%^&amp;*_=+}{'?]+)*@([a-zA-Z0-9_][-a-zA-Z0-9_]*(\.[-a-zA-Z0-9_]+)*\.([cC][oO][mM]))(:[0-9]{1,5})?" maxlength="64">
   <input type="Submit">
</form>

这篇关于模式属性值不是有效的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆