我应该在html5输入正则表达式模式验证中使用^和$吗? [英] Should I use ^ and $ in html5 input regex pattern validation?

查看:418
本文介绍了我应该在html5输入正则表达式模式验证中使用^和$吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我见过大多数没有^(circumflex)和$(货币或美元)字符的例子来标记匹配字符串的结尾。 但是,我在html5规范中没有找到任何相关内容。它们隐含在模式中吗? html5规范声明它们是隐式的。

I've seen mostly examples without the ^ (circumflex) and $ (currency or dollar) characters to mark the beginning an end of the string being matched. However, I did not find anything regarding this in the html5 spec. Are they implicit in the pattern? The html5 spec states that they are implicit.

编译后的模式正则表达式在与字符串匹配时必须具有开始锚定到字符串的开头,并将其结束锚定到字符串的结尾。

这意味着用于此属性的正则表达式语言与JavaScript中使用的正则表达式语言相同,只是模式属性与整个值匹配,而不仅仅是任何子集(有点像暗示) a ^(模式开头的?:和a)最后的$)。
The compiled pattern regular expression, when matched against a string, must have its start anchored to the start of the string and its end anchored to the end of the string. This implies that the regular expression language used for this attribute is the same as that used in JavaScript, except that the pattern attribute is matched against the entire value, not just any subset (somewhat as if it implied a ^(?: at the start of the pattern and a )$ at the end).

在type =text输入中,使用任一格式的模式都可正常工作但是在type =tel输入中,我必须删除正则表达式的字符才能按预期工作。我已经在Opera和Firefox中进行了测试。

In type="text" inputs, the pattern works fine using either format, however in type="tel" inputs, I had to remove the characters for the regex to work as expected. I've tested in both Opera and Firefox.

这是一个浏览器错误吗?我应该在bugzilla等中提交错误吗?

Is this a browser bug? Should I file a bug in bugzilla etc.?

编辑:看来我好像我偶然发现了一个奇怪的错误,因为我无法创建一个简化的测试用例。页面中的简单输入不会显示上述行为。但问题仍然存在。我应该,还是不应该使用darn ^和$ anchors?

It seems that I've stumbled uppon a weird bug, because I'm unable to create a reduced test case. A simple input in a page doesn't shows the behavior stated above. However, the question remains. Should I, or should I not use the darn ^ and $ anchors?

推荐答案

根据标准,正则表达式锚定在开头和结尾。但是,在实践中(经过测试的FF 15和Chrome 21)它只停留在开始!

According to the standard, the regex is anchored at the start and end. However, in practice (tested FF 15 and Chrome 21) it is anchored at the start only!

因此,如果你想兼容标准和现实,你应该用 $ 锚定你的正则表达式明确。是否使用 ^ 也取决于你 - 没有必要。

So if you want to be compatible both with the standard and reality, you should anchor your regex with a $ explicitly. Whether to use ^ also is up to you - it is not necessary.

这篇关于我应该在html5输入正则表达式模式验证中使用^和$吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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