Jacob
Jacob

Reputation: 420

Java Regex for password validation

I have created regex for password validation in a Java app. The regex I created is below for below requirement.

^[\\p{Alnum}#.!@$*&_]{5,12}$
  1. At least 5 chars and max 12 chars
  2. Contains at least one digit
  3. Contains at least one char
  4. may contain chars within a set of special chars (#.!@$*&_)
  5. Does not contain space, tab, etc.

I am missing 1 and 2 like if I give "gjsajhgjhagfj" or "29837846876", it should fail. But it's not happening.

Could anyone help please?

Upvotes: 0

Views: 997

Answers (1)

Enissay
Enissay

Reputation: 4953

You can use lookaheads to force conditions 1 & 2:

^(?i)(?=.*[a-z])(?=.*[0-9])[a-z0-9#.!@$*&_]{5,12}$

DEMO

(?i) is for insensitive match, the same as Pattern.CASE_INSENSITIVE flag for your compile function:

Pattern.compile(regex, Pattern.CASE_INSENSITIVE)

You can read more about Lookaheads HERE

Upvotes: 3

Related Questions