正则密码强度验证Demo

630 阅读1分钟

//设置基础样式
<style>
    #msg {
      width: 100px;
      margin: 20px 0;
      border: 1px solid #ccc;
      display: none;
    }

    #progress {
      width: 100%;
      height: 4px;
    }
</style>

<body>
  <input type="text" id="pwd">
  <div id="msg">
    <div id="progress"></div>
  </div>
</body>

//引入jq
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>

<script>
  $('#pwd').on("input", function () {
    let level = 0;
    let str = $(this).val();
    if (/\d/.test(str)) level++         //有数字强度加1
    if (/[a-z]/.test(str)) level++      //有小写字母强度加1
    if (/[A-Z]/.test(str)) level++      //有大写字母强度加1
    if (str.length > 10) level++        //长度大于10强度加1
    if (/[\.\~\@\#\$\^\&\*]/.test(str)) level++     //有以下特殊字符强度加1
    $('#msg').show()
    let arr = ['red', 'orangered', 'yellow', 'blue', 'green']

    $('#progress').css('width', (level / 5) * 100 + "%")
      .css('background', arr[level - 1])
  })
</script>