React 實(shí)現(xiàn)給密碼輸入框加上【密碼強(qiáng)度】展示?
密碼強(qiáng)度
平時(shí)我們在瀏覽各種網(wǎng)站和 APP 的時(shí)候,都接觸過密碼這個(gè)東西~
密碼設(shè)置的好不好,關(guān)乎到你的賬號(hào)安全性,越復(fù)雜的密碼越安全,所以密碼強(qiáng)度很重要,而我們在做注冊功能的時(shí)候,也有責(zé)任去幫協(xié)助用戶設(shè)置一個(gè)高密碼強(qiáng)度的密碼~
那么密碼強(qiáng)度怎么計(jì)算呢? 且應(yīng)該如何實(shí)現(xiàn)以下這樣的密碼強(qiáng)度動(dòng)畫展示效果呢?
思路
其實(shí)思路很簡單:
(1) 監(jiān)聽密碼輸入框的變化
(2) 密碼變化時(shí),獲取密碼文本,并通過某種方式計(jì)算這個(gè)密碼的強(qiáng)度分?jǐn)?shù)
(3) 根據(jù)強(qiáng)度分?jǐn)?shù),改變下方塊的顏色和寬度
- 0分:強(qiáng)度低,紅色,寬度 20%
- 1分:強(qiáng)度低,紅色,寬度 40%
- 2分:強(qiáng)度中,橙色,寬度 60%
- 3分:強(qiáng)度高,綠色,寬度 80%
- 4分:強(qiáng)度高,綠色,寬度 100%
計(jì)算密碼強(qiáng)度分?jǐn)?shù)
用什么方式去計(jì)算密碼強(qiáng)度方式呢?我們可以用 @zxcvbn-ts/core這個(gè)庫來計(jì)算~
@zxcvbn-ts/core 是 zxcvbn 密碼強(qiáng)度估計(jì)器的 TypeScript 實(shí)現(xiàn)版本,用于幫助開發(fā)者評(píng)估用戶設(shè)置密碼的復(fù)雜度和安全性,計(jì)算的依據(jù)有:
- 密碼長度: 越長分?jǐn)?shù)越高
- 字符類型: 數(shù)字、字母、符號(hào)
- 詞典攻擊檢測: 內(nèi)置詞典列表,檢測密碼強(qiáng)度
- 評(píng)分系統(tǒng): 0-4分,分?jǐn)?shù)越高越安全
- 熵計(jì)算: 評(píng)測密碼所需嘗試次數(shù),熵越高,分?jǐn)?shù)越高
pnpm i @zxcvbn-ts/core
密碼強(qiáng)度動(dòng)畫展示效果
計(jì)算了分?jǐn)?shù)之后,我們需要根據(jù)分?jǐn)?shù)去展示:
- 不同的顏色
- 不同的寬度
我們可以使用屬性選擇器的方式,去完成這一個(gè)效果,看以下代碼~
當(dāng)密碼改變的時(shí)候,會(huì)實(shí)時(shí)計(jì)算密碼強(qiáng)度分?jǐn)?shù),這也就是意味著 data-score 這個(gè)屬性會(huì)一直變,接著我們可以在樣式中,去根據(jù)屬性選擇器去設(shè)置不同的顏色和寬度
現(xiàn)在可以看到這樣的效果
完善動(dòng)畫效果
但是我們?nèi)绻雽?shí)現(xiàn)分格的效果,可以借助偽元素去做~
現(xiàn)在可以達(dá)到我們期望的效果~
完整代碼
import { Input } from 'antd'
import { useMemo, useState } from 'react'
import { zxcvbn } from '@zxcvbn-ts/core'
import './Index.less'
const Index = () => {
const [password, setPassword] = useState('')
const passwordStrength = useMemo(() => {
return zxcvbn(password).score
}, [password])
const onChange: React.ChangeEventHandler<HTMLInputElement> = (e) => {
setPassword(e.target.value)
}
return <>
<Input.Password value={password} onChange={onChange} />
<div className='strength-meter-bar'>
<div className='strength-meter-bar--fill' data-score={passwordStrength}></div>
</div>
</>
}
export default Index
// Index.less
.strength-meter-bar {
position: relative;
height: 6px;
margin: 10px auto 6px;
border-radius: 6px;
background-color: rgb(0 0 0 / 25%);
// 增加的偽元素樣式代碼
&::before,
&::after {
content: '';
display: block;
position: absolute;
z-index: 10;
width: 20%;
height: inherit;
border-width: 0 5px;
border-style: solid;
border-color: #fff;
background-color: transparent;
}
&::before {
left: 20%;
}
&::after {
right: 20%;
}
// 增加的偽元素樣式代碼
&--fill {
position: absolute;
width: 0;
height: inherit;
transition:
width 0.5s ease-in-out,
background 0.25s;
border-radius: inherit;
background-color: transparent;
&[data-score='0'] {
width: 20%;
background-color: darken(#e74242, 10%);
}
&[data-score='1'] {
width: 40%;
background-color: #e74242;
}
&[data-score='2'] {
width: 60%;
background-color: #efbd47;
}
&[data-score='3'] {
width: 80%;
background-color: fade(#55d187, 50%);
}
&[data-score='4'] {
width: 100%;
background-color: #55d187;
}
}
}