JS 密码强度校验的正则表达式(简单且好用)

最近一直在做通行证项目,里面的注册模块中输入密码需要显示密码强度(低中高)。今天就把做的效果给大家分享下,代码没有网上搜索的那么复杂,能够满足一般的需求。

html 代码如下:

<!DOCTYPE HTML>
<html lang="en">
<head>
  <meta charset="utf-8"/>
  <title>密码强度</title>
  <style type="text/css">
  #passStrength{height:6px;width:120px;border:1px solid #ccc;padding:2px;}
  .strengthLv1{background:red;height:6px;width:40px;}
  .strengthLv2{background:orange;height:6px;width:80px;}
  .strengthLv3{background:green;height:6px;width:120px;}
  </style>
</head>
<body>
  <input type="password" name="pass" id="pass" maxlength="16"/>
  <div class="pass-wrap">
    <em>密码强度:</em>
    <div id="passStrength"></div>
  </div>
</body>
</html>
<script type="text/javascript" src="js/passwordStrength.js"></script>
<script type="text/javascript">
new PasswordStrength('pass','passStrength');
</script>

js 代码如下:

function PasswordStrength(passwordID,strengthID){
  this.init(strengthID);
  var _this = this;
  document.getElementById(passwordID).onkeyup = function(){
    _this.checkStrength(this.value);
  }
};
PasswordStrength.prototype.init = function(strengthID){
  var id = document.getElementById(strengthID);
  var div = document.createElement('div');
  var strong = document.createElement('strong');
  this.oStrength = id.appendChild(div);
  this.oStrengthTxt = id.parentNode.appendChild(strong);
};
PasswordStrength.prototype.checkStrength = function (val){
  var aLvTxt = ['','低','中','高'];
  var lv = 0;
  if(val.match(/[a-z]/g)){lv++;}
  if(val.match(/[0-9]/g)){lv++;}
  if(val.match(/(.[^a-z0-9])/g)){lv++;}
  if(val.length < 6){lv=0;}
  if(lv > 3){lv=3;}
  this.oStrength.className = 'strengthLv' + lv;
  this.oStrengthTxt.innerHTML = aLvTxt[lv];
};

效果图:

使用说明:

1、对象的第一个参数是密码输入框的 id,第二个参数是密码强度长条的 id。

2、checkStrength 方法中可以自定义密码强度的规则。

3、密码强度显示低中高分别对应 3 个 css 样式(strengthLv1、strengthLv2、strengthLv3)。

以上所述是小编给大家介绍的JS 密码强度校验的正则表达式,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对来客网网站的支持!