温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

js如何验证密码强度

发布时间:2020-09-21 14:02:13 来源:脚本之家 阅读:325 作者:Kevin''''''''''''''' 栏目:web开发

验证“密码强度”的例子很常见,我们注册新的账号的时候往往设置密码,此时就遇到验证密码强度的问题了。“密码强度”也就是密码难易程度的意思。

原理:

1、如果输入的密码为单纯的数字或者字母:提示“

2、如果是数字和字母混合的:提示“” 

3、如果数字、字母、特殊字符都有:提示“

下面是一种“密码强度”的验证方法,觉得很有意思。

HTML和CSS代码:

<!DOCTYPE HTML>
<html > <!-- lang="en" -->
<head>
 <meta charset="utf-8" />
 <title>密码强度</title>
 <style type="text/css">
 
 #pwdStrength {
  height: 30px;
  width: 180px;
  border: 1px solid #ccc;
  padding: 2px;
  
 } 
 .strengthLv1 {
  background: red;
  height: 30px;
  width: 60px;
 }
 
 .strengthLv2 {
  background: orange;
  height: 30px;
  width: 120px;
 }
 
 .strengthLv3 {
  background: green;
  height: 30px;
  width: 180px;
 }
 #pwd {
  height:30px;
  font-size :20px;
 }
 strong {
  margin-left:90px;
 }
 #pwd1 {
  color:red;
  margin-top:5px;
  margin-bottom:5px;  
 }
 </style>
</head>
<body>
 <input type="password" name="pwd" id="pwd" maxlength="16" />
 <div class="pass-wrap">
 <!--<em>密码强度:</em>-->
 <p id="pwd1" name="pwd">密码强度:</p>
 <div id="pwdStrength"></div>
 </div>
</body>
</html>

javascript代码:

<script type="text/javascript">
 function PasswordStrength(passwordID, strengthID) {
 this.init(strengthID);
 var _this = this;
 document.getElementById(passwordID).onkeyup = function () {//onkeyup 事件,在键盘按键被松开时发生,进行判断
  _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; } //如果密码长度小于6位,提示消息为空
 if (lv > 3) { lv = 3; } 
 this.oStrength.className = 'strengthLv' + lv;
 this.oStrengthTxt.innerHTML = aLvTxt[lv];
 };
new PasswordStrength('pwd','pwdStrength');
</script>

效果图:

js如何验证密码强度

小结:

1.利用onkeyup 事件(在键盘按键被松开时发生)进行三种判断,简单方便。
2. 正则表达式的功能真的很强大。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI