我需要编写一个特殊字符的java字符串和0到9之间的数字来验证密码

时间:2018-01-17 12:47:44

标签: java validation passwords

我需要编写一个特殊字符的java字符串和0到9之间的数字来验证密码,所以我创建了一个接收String并返回字符串的方法,如下所示,,,, 但是我不能为所有特殊字符写一个字符串,而另一个字符串写0到9的数字

public String isPasswordvalid(String password) {

    String x = password;
    String specialChars = "(.*[,~,!,@,#,$,%,^,&,*,(,),-,_,=,+,[,{,],},|,;,:,<,>,/,?].*$)";
    String passwordNumbers = "(.*[0-9].*)";
    String minSixCharacterErrorMessage = "Invalid password,Password should be at least 6 character ";
    String emptyFieldErrorMessage = "Invalid password,Field is empty , please enter a Valid password";
    String missingSpecialCharacterErrorMessage = "Invalid password, It must contains a special charctar";
    String numberErrorMessage = "Invalid password, It must contains at least one number";
    String noSpaceCharacterErrorMessage = "Invalid password, Password cant contains spaces";

    if (x.isEmpty()) {
        // System.out.println("Field is empty , please enter a Valid password");
        return emptyFieldErrorMessage;


    } else if (x.length() < 6) {
        // System.out.println("Password should be min 6 character ");
        return minSixCharacterErrorMessage;

    } else if (!x.contains(specialChars)) {
        //System.out.println("Invalid password, It must contains a special charctar");
        return missingSpecialCharacterErrorMessage;

    } else if (!x.contains(passwordNumbers)) {
        //System.out.println("Invalid password, It must contains at least one number");
        return numberErrorMessage;

    } else if (x.contains(" ")) {
        //System.out.println("Invalid password, Password cant contains spaces");
        return noSpaceCharacterErrorMessage;


    }

    return "";


}

1 个答案:

答案 0 :(得分:0)

contains不使用正则表达式。您可能希望查看matches。还要检查链接的javadoc以供参考。