正则表达式测试工作但在传递给HTML5输入模式属性时中断

时间:2016-05-01 20:44:39

标签: regex html5 validation input

我试图在密码字段上使用此模式,该密码字段显示"密码应为最小6个字符并包含1个非字母字符":

^(?=.{6})(?=.*[^a-zA-Z])

但是,当将其传递到pattern属性时,它将停止工作。查看此演示:



document.querySelector('form').addEventListener("submit", onFormSubmit);

function onFormSubmit(e) {
  e.preventDefault();
  var pwEl = document.querySelector('.password');
  
  alert('With pattern: ' + pwEl.checkValidity() + ', without pattern: ' + /^(?=.{6})(?=.*[^a-zA-Z])/.test(pwEl.value));
}

<form novalidate>
  
  <input class="password" type="password" placeholder="Enter password" pattern="^(?=.{6})(?=.*[^a-zA-Z])" />
  
  <button type="submit">submit</button>
  
</form>
&#13;
&#13;
&#13;

尝试输入:

  • &#34;密码&#34;两者都是假的
  • &#34;密码1&#34;模式是假的,但具有相同模式的正则表达式

0 个答案:

没有答案