java swing注册表窗体密码弱点条件

7xzttuei  于 2021-06-30  发布在  Java
关注(0)|答案(2)|浏览(287)

我想用java做一个注册系统。进展很顺利。我只有一个具体的问题。密码的弱点。我做的,密码必须超过8个字符与一个简单的

if(password.getText().length() > 8) { error message }

我还提出了这样一个条件:

if(... < 8 || !(password.getText().contains("1"))) { error message }

但在这个条件下,它只接受密码,如果你的密码例如:asdfghjk1,所以我尝试了很多| |条件,如!。。。。包含(“2”)!。。包含(“9”)
但在这些条件下,它只在密码为:123456789时起作用,但我真正想做的是一个密码,长度超过8个字符,至少包含一个大写字母和一个数字。有办法吗?顺便说一下,我使用javaswing。

col17t5w

col17t5w1#

你可以用正则表达式,但我不知道怎么做。但这应该行得通:
在这里验证密码:string passwordstring=password.gettext();

if (passwordString.Length() > 8 && checkCapital(passwordString) && checkDigit(passwordString)){ valid password }

else { error message }

这是我使用的ascii码:

private static boolean checkCapital(String string) {
    for (char c : string.toCharArray()) {
        int code = (int) c;
        if (code >= 65 && code <= 90) 
            return true;
    }
    return false;
}

这是校验位:

private static boolean checkDigit(String string) {
    for (int i = 0; i < 10; i++) {
        if (string.contains("" + i))
            return true;
    }
    return false;
}
knpiaxh1

knpiaxh12#

解决这个问题的最好方法是使用regex。这里我给你举一个如何使用regex检查密码的例子。

import java.util.regex.*; 
class GFG { 

    // Function to validate the password. 
    public static boolean
    isValidPassword(String password) 
    { 

        // Regex to check valid password. 
        String regex = "^(?=.*[0-9])"
                       + "(?=.*[a-z])(?=.*[A-Z])"
                       + "(?=.*[@#$%^&+=])"
                       + "(?=\\S+$).{8,20}$"; 

        // Compile the ReGex 
        Pattern p = Pattern.compile(regex); 

        // If the password is empty 
        // return false 
        if (password == null) { 
            return false; 
        } 

        // Pattern class contains matcher() method 
        // to find matching between given password 
        // and regular expression. 
        Matcher m = p.matcher(password); 

        // Return if the password 
        // matched the ReGex 
        return m.matches(); 
    } 

    // Driver Code. 
    public static void main(String args[]) 
    { 

        // Test Case 1: 
        String str1 = "Thuans@portal20"; 
        System.out.println(isValidPassword(str1)); 

        // Test Case 2: 
        String str2 = "DaoMinhThuan"; 
        System.out.println(isValidPassword(str2)); 

        // Test Case 3: 
        String str3 = "Thuan@ portal9"; 
        System.out.println(isValidPassword(str3)); 

        // Test Case 4: 
        String str4 = "1234"; 
        System.out.println(isValidPassword(str4)); 

        // Test Case 5: 
        String str5 = "Gfg@20"; 
        System.out.println(isValidPassword(str5)); 

        // Test Case 6: 
        String str6 = "thuan@portal20"; 
        System.out.println(isValidPassword(str6)); 
    } 
}

输出:true false false
您也可以通过以下链接参考类似主题:
用于密码的regex java

相关问题