1

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

  • at least 1 number
  • at least 1 alphabet character
  • at least 1 character from set !@#$%^&*()_+=-~`][{};':"/.>?,<
  • 8 to 20 characters

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 ?

Thai Tran
  • 9,815
  • 7
  • 43
  • 64
  • try `[a-zA-Z]+\\d+[!@#$%^&*()]+` You may want to quote the special chars if they have special meaning this is just off the topof my head... – Thihara Dec 17 '12 at 03:16
  • possible duplicate of [Regular Expression for password validation](http://stackoverflow.com/questions/2370015/regular-expression-for-password-validation) – Dante May Code Dec 17 '12 at 03:47

3 Answers3

3

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);
steveha
  • 74,789
  • 21
  • 92
  • 117
1

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

  • very good library, indeed. But adding 1 more extra lib to my project requires lot of discussion. Thank, anw :D – Thai Tran Dec 17 '12 at 03:42
0

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.

Community
  • 1
  • 1
rbtLong
  • 1,542
  • 3
  • 14
  • 31