一、第一种
规则
先展示效果
具体规则
- 长度显最小8位
- 需有字母大小写
- 需有数字
- 需有特殊字符(暂无限制字符类型)
实现
- 定义组件
password-strength.vue
<template>
<div class="password-strength" v-if="input > -1">
<b :style="{backgroundColor: strengthType.arr[0]}"></b>
<b :style="{backgroundColor: strengthType.arr[1]}"></b>
<b :style="{backgroundColor: strengthType.arr[2]}"></b>
<b :style="{backgroundColor: strengthType.arr[3]}"></b>
<b :style="{backgroundColor: strengthType.arr[4]}"></b>
<span>
{{ strengthType.tip }}
</span>
</div>
</template>
<script lang="ts">
import { computed } from 'vue'
export default {
name: 'PasswordStrength',
props: {
modelValue: {
type: Number,
default: -1
}, // 组件绑定值
},
setup(props, { emit }) {
const input = computed({
get() {
return props.modelValue
},
set(val) {
emit('update:modelValue', val)
}
})
const strengthType = computed(() => {
let result = {
tip: '',
arr: ['transparent', 'transparent', 'transparent', 'transparent', 'transparent']
}
switch (input.value) {
case 0:
result.arr[0] = 'red'
result.tip = 'Unsafe'
break;
case 1:
result.arr[0] = 'yellow'
result.arr[1] = 'yellow'
result.arr[2] = 'yellow'
result.tip = 'Normal safety'
break;
case 2:
result.arr[0] = 'yellow'
result.arr[1] = 'yellow'
result.arr[2] = 'yellow'
result.arr[3] = 'yellow'
result.tip = 'Normal safety'
break;
case 3:
result.arr[0] = 'green'
result.arr[1] = 'green'
result.arr[2] = 'green'
result.arr[3] = 'green'
result.arr[4] = 'green'
result.tip = 'Safety'
break;
default:
break;
}
return result
})
return {
input,
fieldProperty,
strengthType
}
},
}
</script>
<style lang="less" scoped>
.password-strength{
b{
float: left;
width: 30px;
height: 15px;
border: 1px solid;
margin: 5px 2px;
}
span{
margin-left: 50px;
}
}
</style>
- 根据密码输入判断强度
const checkpassword = (password: string) => {
let lvl = 0;//默认是0级
if (!password || password.length < 8) return lvl;
if (/[0-9]/.test(password)) { //密码中是否有数字,或者是字母,或者是特殊符号
lvl++;
}
if (/[a-z]/.test(password)) { // 判断密码中有没有字母
lvl++;
}
if (/[A-Z]/.test(password)) { // 判断密码中有没有字母
lvl++;
}
var _spcialWord = password.replace(/[0-9]/g, '').replace(/[a-z]/g, '').replace(/[A-Z]/g, '').replace(/\s/g, '')
if (_spcialWord && _spcialWord.length > 0) { // 判断密码中有没有特殊符号
lvl++;
}
return lvl;// 最小的值是1,最大值是3
}