简体   繁体   中英

Regular expression for hyphen in password

want to allow hyphen in password validation, below are the cases-
1. must contain mixed case
2. length must be 8 to 32
3. at least one special character. (only that are visible on keyboard).

I have made it,
((?=.*\\\\d)(?=.*[az])(?=.*[AZ])(?=.*[!@#$%^&*()_'\\"+={};:<>,.?/]).{8,32})
but it does not allow hyphen , so where to put hyphen so it includes hyphen in special character set.

You need to allow hyphen - in your character class.

Try this regex:

^(?=.*?\\d)(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[!@#$%^&*()_'\"+={};:<>,.?/-]).{8,32})$

You can probably build a regex that does all the checks in one go, but I would suggest the following approach instead:

private static boolean isPasswordValid(String password) {
    boolean valid = true;
    // at least one lowercased char
    valid &= password.matches(".*[a-z].*");
    // at least one uppercased char
    valid &= password.matches(".*[A-Z].*");
    // at least one digit
    valid &= password.matches(".*[0-9].*");
    // at least one special char
    valid &= password.matches(".*[!@#$%^&*()_'\"+={};:<>,.?/-].*");
    // length & no other char
    valid &= password.matches("[a-zA-Z0-9!@#$%^&*()_'\"+={};:<>,.?/-]{8,32}");
    return valid;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM