woff 發表於 2020-3-12 20:45:16

密碼強度指示套件 - jQuery Password Strength Indicator

前言
最近客戶想做密碼強度指示器,讓用戶輸入密碼的時候,即時知道自己的密碼複雜度

但一想到要自己去"定義"怎樣的密碼複雜度算弱or強,整個人就惰性大發XD(畢竟牽扯JS邏輯+UI bar條+配給CSS顏色)

幸好網路上找來找去,有找到一個簡單好用好上手的套件,也就是本文的主角:「jQuery Password Strength Indicator」


Demo畫面

實作
首先到 https://github.com/matoilic/jquery.pwstrength 下載整包.zip檔並且解壓縮

然後把 jquery.pwstrength.js 放到自己的Web專案目錄

由於官方的CSS檔(路徑:jquery.pwstrength-master\demo\style.css)和頁面設計混在一塊,所以我自行額外抽出如下↓


/*密碼強度指示*/


#pwindicator {
    margin-top: 4px;
    /*width: 150px;*//*官網有這個,但好像有加沒加都沒差,所以拿掉*/
}

/*官方只有寫 .bar,為了避免和自己Web專案有衝突,Selector改寫如下*/
#pwindicator > .bar {
    margin-bottom: 2px; /*這官網沒有,視自己專案需求要不要加。沒加的話,可能bar條和文字會上下黏一塊*/
    height: 2px;
}

#pwindicator > .label {
/*顯示弱、中、強的文字大小,此Selector官方沒有,自己加的*/
font-size: 12px;
}


/*以下顏色自行配*/
/*非常弱*/
.pw-very-weak .bar {
    background: #d00;
    width: 30px;
}

.pw-very-weak .label {
    color: #d00;
}

.pw-weak .bar {
    background: #d00;
    width: 60px;
}

.pw-weak .label {
    color: #d00;
}

.pw-mediocre .bar {
    background: #f3f01a;
    width: 90px;
}

.pw-mediocre .label {
    color: #f3f01a;
}

.pw-strong .bar {
    background: #f3b31a;
    width: 120px;
}

.pw-strong .label {
    color: #f3b31a;
}

.pw-very-strong .bar {
    background: #0d0;
    width: 150px;
}

.pw-very-strong .label {
    color: #0d0;
}
/*End密碼強度指示*/

剩下來的是Html Code,當然要先引用jQuery、再引用 jquery.pwstrength.js

以下是完整代碼

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Test</title>
    <!--引用CSS-->
    <link href="MyStyle.css" rel="stylesheet" />
</head>
<body>

    <!--留意要加上data attribute-->
    <input type="password" name="PD" data-indicator="pwindicator" />
    <div id="pwindicator">
      <div class="bar"></div>
      <div class="label"></div>
    </div>

    <!--引用jQuery-->
    <script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <!--密碼強度指示器-->
    <script src="jquery.pwstrength.js"></script>
    <script type="text/javascript">
      $(function () {
            //啟用密碼強度指示器,並變更說明文字
            $("input").pwstrength({ texts: ['非常弱', '弱', '中等', '強', '非常強'] });

      });
    </script>
</body>
</html>參考文章https://dotblogs.com.tw/shadow/2018/05/24/175916

頁: [1]
查看完整版本: 密碼強度指示套件 - jQuery Password Strength Indicator