How to validate a password (must contain uppercase, lowercase, digit, and special character) in Java

1 Answer

0 votes
public class PasswordCheck {

    // One function that checks if the password is valid
    public static boolean isValidPassword(String pass) {
        boolean upper = false, lower = false, digit = false, special = false;
        String specials = "!@#$%^&*";

        for (char ch : pass.toCharArray()) {
            if (Character.isUpperCase(ch)) upper = true;
            else if (Character.isLowerCase(ch)) lower = true;
            else if (Character.isDigit(ch)) digit = true;
            else if (specials.indexOf(ch) != -1) special = true;
        }

        return upper && lower && digit && special;
    }

    public static void main(String[] args) {
        String password1 = "aT5#op09!";
        if (isValidPassword(password1))
            System.out.println("Valid password");
        else
            System.out.println("Invalid password");

        String password2 = "aT#opQ!";
        if (isValidPassword(password2))
            System.out.println("Valid password");
        else
            System.out.println("Invalid password");
    }
}



/*
run:

Valid password
Invalid password

*/

 



answered Apr 25 by avibootz

Related questions

...