侧边栏壁纸
博主头像
Stars-One的杂货小窝博主等级

所有的创作都是有价值的

  • 累计撰写 258 篇文章
  • 累计创建 46 个标签
  • 累计收到 27 条评论

目 录CONTENT

文章目录

Java/Kotlin 密码复杂规则校验

Stars-one
2022-01-17 / 0 评论 / 0 点赞 / 414 阅读 / 3656 字

每次有那个密码复杂校验,不会写正则表达式,每次都去搜,但有时候校验的条件又是奇奇怪怪的,百度都搜不到

找到了个代码判断的方法,每次匹配计算匹配的次数,最后在用次数来作为判断是否满足的条件即可

Java

package site.starsone.demo;

public class CheckPwdUtils {
    //数字
    public static final String REG_NUMBER = ".*\\d+.*";
    //小写字母
    public static final String REG_UPPERCASE = ".*[A-Z]+.*";
    //大写字母
    public static final String REG_LOWERCASE = ".*[a-z]+.*";
    //特殊符号
    public static final String REG_SYMBOL = ".*[~!@#$%^&*()_+|<>,.?/:;'\\[\\]{}\"]+.*";

    /**
     * 长度至少minLength位,且最大长度不超过maxlength,须包含大小写字母,数字,特殊字符matchCount种以上组合
     * @param password 输入的密码
     * @param minLength 最小长度
     * @param maxLength 最大长度
     * @param matchCount 次数
     * @return 是否通过验证
     */
    public static boolean checkPwd(String password,int minLength,int maxLength,int matchCount){
        //密码为空或者长度小于8位则返回false
        if (password == null || password.length() <minLength || password.length()>maxLength ) return false;

        int i = 0;
        if (password.matches(REG_NUMBER)) i++;
        if (password.matches(REG_LOWERCASE))i++;
        if (password.matches(REG_UPPERCASE)) i++;
        if (password.matches(REG_SYMBOL)) i++;
        return i >= matchCount;
    }
}

使用

//长度至少为8位,最大为20位,包含数字 小写字母 大写字母 特殊符号任意两种及以上
CheckPwdUtils.checkPwd("123456", 8, 20, 2)

Kotlin

object CheckPwdUtils {
    //数字
    const val REG_NUMBER = ".*\\d+.*"

    //小写字母
    const val REG_UPPERCASE = ".*[A-Z]+.*"

    //大写字母
    const val REG_LOWERCASE = ".*[a-z]+.*"

    //特殊符号
    const val REG_SYMBOL = ".*[~!@#$%^&*()_+|<>,.?/:;'\\[\\]{}\"]+.*"

    /**
     * 长度至少minLength位,且最大长度不超过maxlength,须包含大小写字母,数字,特殊字符matchCount种以上组合
     * @param password 输入的密码
     * @param minLength 最小长度
     * @param maxLength 最大长度
     * @param matchCount 次数
     * @return 是否通过验证
     */
    fun checkPwd(password: String, minLength: Int, maxLength: Int, matchCount: Int): Boolean {
        //密码为空或者长度小于8位则返回false
        if (password.length < minLength || password.length > maxLength) return false
        var i = 0
        if (password.matches(Regex(REG_NUMBER))) i++
        if (password.matches(Regex(REG_LOWERCASE))) i++
        if (password.matches(Regex(REG_UPPERCASE))) i++
        if (password.matches(Regex(REG_SYMBOL))) i++
        return i >= matchCount
    }
}

使用

val pwd = "123456"
//长度至少为8位,最大为20位,包含数字 小写字母 大写字母 特殊符号任意两种及以上
CheckPwdUtils.checkPwd(pwd, 8, 20, 2)
0

评论区