首页 > 解决方案 > 如何使用大写和数字的正则表达式验证匹配密码并确认密码

问题描述

我想匹配密码并确认密码还对至少 8 个字符、至少 1 个大写字符和至少 1 个数字进行正则表达式验证,到目前为止我已经完成了代码,在控制台正则表达式匹配中给出了 null。提前致谢

var pass = $("#password").val();
var cpass = $("#cnfpassword").val();
var passformat = "/^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])([a-zA-Z0-9]{8})$/";

console.log(pass, cpass);
console.log(passformat.match(pass));
if (passformat.match(pass)) {
  console.log(pass.match(passformat));
  if (pass == cpass) {

    document.getElementById('alertmsg').innerHTML = "Password Matched!";
    // return true;
  } else {
    document.getElementById('alertmsg').innerHTML = "Password Did not match!";
    //     return false;
  }
} else {
  document.getElementById('alertmsg').innerHTML = "password must be at least 8 characters contain capital letters,and number!!!";
  // return false;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group mt-2">
  <input type="password" class="form-control" id="password" aria-describedby="password" placeholder="Enter a password" style="width: 80%; margin: auto;" required onkeyup="ValidatePassword()">
</div>
<div class="form-group mt-2">
  <input type="password" class="form-control" id="cnfpassword" aria-describedby="cnfpassword" placeholder="Repeat your password" style="width: 80%; margin: auto;" required onkeyup="ValidatePassword()">
</div>

标签: javascripthtml

解决方案


最少 8 个字符的正则表达式,并且至少包含 1 个大写字母、1 个小写字母、1 个数字、1 个特殊字符

const myRegEx = new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{8,})");

myRegEx.test(password)

推荐阅读