当前位置: 移动技术网 > IT编程>开发语言>JavaScript > JS高级---案例:验证密码的强度

JS高级---案例:验证密码的强度

2020年01月15日  | 移动技术网IT编程  | 我要评论

案例:验证密码的强度

 

1. 给我密码,我返回对应的级别

2. 每次键盘抬起都要获取文本框中的内容, 验证文本框中有什么东西, 得到一个级别, 然后下面的div显示对应的颜色

 

<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <title>document</title>
</head>
<style type="text/css">
  #dv {
    width: 300px;
    height: 200px;
    position: absolute;
    left: 300px;
    top: 100px;
  }

  .strengthlv0 {
    height: 6px;
    width: 120px;
    border: 1px solid #ccc;
    padding: 2px;
  }

  .strengthlv1 {
    background: red;
    height: 6px;
    width: 40px;
    border: 1px solid #ccc;
    padding: 2px;
  }

  .strengthlv2 {
    background: orange;
    height: 6px;
    width: 80px;
    border: 1px solid #ccc;
    padding: 2px;
  }

  .strengthlv3 {
    background: green;
    height: 6px;
    width: 120px;
    border: 1px solid #ccc;
    padding: 2px;
  }
</style>

<body>
  <div id="dv">
    <label for="pwd">密码</label>
    <input type="text" id="pwd" maxlength="16">
    <!--课外话题-->
    <div>
      <em>密码强度:</em>
      <em id="strength"></em>
      <div id="strengthlevel" class="strengthlv0"></div>
    </div>
  </div>
  <script src="common.js"></script>
  <script>

    //获取文本框注册键盘抬起事件
    my$("pwd").onkeyup = function () {
      //每次键盘抬起都要获取文本框中的内容,验证文本框中有什么东西,得到一个级别,然后下面的div显示对应的颜色
      //如果密码的长度是小于6的,没有必要判断
      my$("strengthlevel").classname = "strengthlv" + (this.value.length >= 6 ? getlvl(this.value) : 0);
    };

    //给我密码,我返回对应的级别
    function getlvl(pwd) {
      var lvl = 0;//默认是0级
      //密码中是否有数字,或者是字母,或者是特殊符号
      if (/[0-9]/.test(pwd)) {
        lvl++;
      }
      //判断密码中有没有字母
      if (/[a-za-z]/.test(pwd)) {
        lvl++;
      }
      //判断密码中有没有特殊符号
      if (/[^0-9a-za-z_]/.test(pwd)) {
        lvl++;
      }
      return lvl;//最小的值是1,最大值是3
    }

  </script>


</body>

</html>

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网