-1

I faced some problem while validating a password that will contain minimum 5 characters using regex.

I am using a very simple regex as below:

String PASSWORD_PATTERN_MIN_CHARS = "(?=.*[a-z|A-Z]{5,}).{8,}";

The regex says password must contains minimum 5 characters and minimum 8 chars will be passwrd length.

It is working fine for "aasaT124" String. But fails for "aa12sa4T".

Clearly the difference is regex matches only if the characters are sequential.

The String for which validation fails also contains minimum 5 characters.

assylias
  • 321,522
  • 82
  • 660
  • 783
AnjanN
  • 603
  • 1
  • 5
  • 9
  • `Pls provide the simple Regex for this sample. Dont post complicated regex's.` -- You're *inviting* folks to close the post. – devnull Aug 05 '13 at 06:57
  • 2
    What's wrong with `[a-zA-Z0-9]{5,8}`? That's as simple as it can get. – Buhake Sindi Aug 05 '13 at 06:58
  • 1
    What is "The regex says password must contains minimum 5 characters and minimum 8 chars will be passwrd length." supposed to mean? did you mean a minimum of 5 and a maximum of 8? – Michael Aug 05 '13 at 06:58
  • It might be that you should try to use something other than regexes for this. Or if you must use them, then use several. The string library is very robust. Use it! Regexes are tough to maintain and tough to read for humans. They have their place but they don't always belong everywhere. – scott_fakename Aug 05 '13 at 06:58
  • 3
    For the love of god, never actually use this for anything. Never assign a maximum length to your passwords, and never assign a minimum of less than 10. And don't require ASCII, either. Let them enter whatever the hell they want. – Chris Hayes Aug 05 '13 at 07:02
  • 1
    Upvoting question because I think others may learn from it as how not to handle passwords. Also upvoting @ChrisHayes' answer because of the last sentence. – András Hummer Aug 05 '13 at 07:08
  • Do a search for password validation. There are lots of good answers that should help. e.g. [Regular expression for a string that must contain minimum 14 characters, where at minimum 2 are numbers, and at minimum 6 are letters](http://stackoverflow.com/a/5527428/433790) – ridgerunner Aug 05 '13 at 13:27

3 Answers3

1

Try out this

(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{5,}.{8,}$/)
Pandiyan Cool
  • 6,381
  • 8
  • 51
  • 87
1

This regex says that string must contains 5 letters and at least 8 characters (letters + digits)

(?=(.*[a-zA-Z]){5})^[0-9a-zA-Z]{8,}$
jtomaszk
  • 9,223
  • 2
  • 28
  • 40
1

I recommend a special purpos library like vtpassword. You can define rules that a password has to match.

List<Rule> rules = new ArrayList<>();
rules.add(new LengthRule(8, 99));
rules.add(new LowercaseCharacterRule(5));
PasswordValidator validator = PasswordValidator(rules);

RuleResult ruleResult =
  validator.validate(new PasswordData(new Password("aasaT124")));
if (ruleResult.isValid()) {
  // OK
}