在 JS 中,我可以运行:
/[a-z]/.test('foo');
返回 true
,因为单个小写字符出现在字符串中的任何位置。
但是:
<input pattern="[a-z]" value="foo" required />
和
console.log(document.querySelector('input').checkValidity())
返回 false
。
为什么 HTML5 checkValidity 返回与 JavaScript regexp.test() 不同的结果?
最佳答案
A regular expression that the control's value is checked against. The pattern must match the entire value, not just some subset.
— https://developer.mozilla.org/en/docs/Web/HTML/Element/Input
因此 pattern="[a-z]"
等同于 /^[a-z]$/.test('foo');
关于javascript - 为什么 HTML5 checkValidity() 返回的结果与 JavaScript regexp.test() 不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28149635/