regex - 我应该在 html5 输入正则表达式模式验证中使用 ^ 和 $ 吗?

标签 regex html validation browser-bugs

我看到的大部分示例都没有使用 ^(抑扬符)和 $(货币或美元)字符来标记匹配字符串的开头和结尾。 但是,我在 html5 规范中没有找到任何关于此的内容。它们是否隐含在模式中?html5 规范声明它们是隐含的。

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 中进行了测试。

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


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

最佳答案

关于 the pattern attribute 的 HTML 标准部分仍然说它总是锚定在开始和结束,正如问题中已经引用的那样:

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.

我们可以使用一个简单的测试片段来确认这种行为:

<form>
  <input required pattern="abc">
  <button>Submit</button>
</form>

您会注意到上面的表单拒绝了 foo abcabc foo 的值;只有完全输入字符串 abc 才会被接受。这表明 pattern="abc" 等同于 pattern="^abc$" 并且您不需要指定 ^$ 显式。

据我所知,competing answer这里声称浏览器用于实现不同的行为,违反规范,是完全错误的。您可以从 https://ftp.mozilla.org/pub/firefox/releases/15.0/win32/en-GB/ 下载 Firefox 15并亲自测试上面的代码片段,您会发现其行为就像在现代浏览器中一样。或者,由于您可能不会被打扰,您可以查看我为您执行此操作的屏幕截图:

Screenshot of this answer in Firefox 15 showing the form above rejecting input of "abc foo"

关于regex - 我应该在 html5 输入正则表达式模式验证中使用 ^ 和 $ 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9142208/

相关文章:

html - 当文本变短时,不应用文本和图像的左右浮动

C++ 数据验证工作不正常和 PDB 错误?

python - 向具有三个独立输入的函数添加输入验证

regex - 正则表达式仅返回 1 个匹配项

regex - 如何从 Scala 中的文本中删除数字?

regex - 用制表符替换空格缩进 (PCRE)

html - 将复选框与 td 内的文本对齐

JavaScript : parse float with string prefix in both start and end

javascript - $(this).val() 不适用于 FireFox 但适用于 Chrome

javascript - HTML5 验证 : JavaScript weirdness with willValidate