JS实现检查密码强度函数

编写一个JS函数,基于如下规则确定给定密码的强度。

目录

一、函数要求

二、示例输出

三、约束条件

四、程序代码


一、函数要求

1、如果只包含数字,而且少于 8 个字符,则为非常弱的密码。
2、如果只包含字母,而且少于 8 个字符,则为弱密码。
3、 如果包含字母,至少有一个数字,而且不少于 8 个字符,则为强密码。
4、如果包含字母、数字和特殊字符,而且不少于 8 个字符,则为非常强的密码。

二、示例输出

三、约束条件

创建 passwordValidator 函数,以密码为参数。

四、程序代码

function passwordValidator(password) {
    const hasNumber = /\d/.test(password);
    const hasLetter = /[a-zA-Z]/.test(password);
    const hasSpecialChar = /[!@#$%^&*(),.?":{}|<>]/.test(password);
    const length = password.length;
    const str = `密码:[${password}]是一个`
    if (hasNumber && hasLetter && hasSpecialChar && length >= 8) {
        return str + '非常强的密码';
    } else if (hasNumber && hasLetter && length >= 8) {
        return str + '强密码';
    } else if (hasLetter && length < 8) {
        return str + '弱密码';
    } else if (length < 8) {
        return str + '非常弱的密码';
    } else {
        return str + '密码不符合任何规则';
    }
}

console.log(passwordValidator("12345"))
console.log(passwordValidator("abcdef"))
console.log(passwordValidator("abc123xyz"))
console.log(passwordValidator("1337h@xor"))

猜你喜欢

转载自blog.csdn.net/qq_19309473/article/details/131302416