Thai Tran
Thai Tran

Reputation: 9935

Regular expression for validation

I need to verify a password string by using Java. This is the requirement of validation:

After screwing around and banging my head to the wall several times, I came up with this regular expression

if (!password.matches("^(?=.+[0-9])(?=.+[a-zA-Z])(?=.+[\\x21-\\x2F\\x3A-\\x40\\x5B-\\x60\\x7B-\\x7E])[0-9a-zA-Z\\x21-\\x2F\\x3A-\\x40\\x5B-\\x60\\x7B-\\x7E]{8,20}$")) {

}

which looks too awful and insane. Is there any better way to achieve this mission ?

Upvotes: 1

Views: 303

Answers (3)

user180100
user180100

Reputation:

With guava CharMatcher.

// at least 1 number
CharMatcher.inRange('0', '9').countIn(password) >= 1 && 
// at least 1 alphabet character
CharMatcher.inRange('a', 'z').or(inRange('A', 'Z')).countIn(password) >= 1 && 
// at least 1 character from set !@#$%^&*()_+=-~`][{};':"/.>?,<
CharMatcher.anyOf("!@#$%^&*()_+=-~`][{};':\"/.>?,<").countIn(password) >= 1 && 
// 8 to 20 characters
password.length() >= 8 && password.length() <= 20

this assumes you want latin alphabet

Upvotes: 1

steveha
steveha

Reputation: 76765

I recommend using the regular expressions for what they do best, but using code for things that the regexp doesn't do well. Something like this. (Sorry, I haven't tested this code, but it should give the idea even if I made a mistake and it won't run.)

Pattern special_chars = Pattern.compile("[!@#$%^&*()_+=-~`\][{};':\"/.>?,<]");
Pattern number_chars = Pattern.compile("[0-9]");
Pattern letter_chars = Pattern.compile("[a-zA-Z]");

boolean valid;

valid = (special_chars.matcher(password).find() &&
        number_chars.matcher(password).find() &&
        letter_chars.matcher(password).find() &&
        8 <= password.length() && password.length() <= 20);

Upvotes: 3

rbtLong
rbtLong

Reputation: 1582

i believe this has already been answered.

Regular Expression for password validation

but may i suggest that you split up the validation into the respective categories? this way it may be easier and you will be able to tell the user exactly what they're missing.

Upvotes: 0

Related Questions