views:

69

answers:

2

Can someone help me to validate the following rules using a RegEx pattern

Max length : 15
Minimum length : 6
Minimum character count : 1
Minimum numbers count : 1
Consequent repeated character count : 2

+2  A: 

I suggest you use a few different regex patterns to check for all those rules cause it will either be impossible or very complicated.

  • .length to check the first 2 rules
  • [a-z] (with case insensitive option) for the 3rd rule
  • \d for the 4th rule
  • (.)\1{2,} for the 5th rule, if this one matches the string contains 3+ character repetitions
Fabian
+1: simple and easy to understand
Michał Niklas
The last one won't catch a password like `a0!!!!`. Also, `\a-z` is invalid, you probably mean `[a-z]`.
Tim Pietzcker
@Tim, corrected my answer even tho yours has already been accepted
Fabian
+4  A: 
^                   # start of string
(?=.{6,15}$)        # assert length
(?=.*[A-Za-z])      # assert letter
(?=.*[0-9])         # assert digit
(?:(.)(?!\1\1))*    # assert no more than 2 consecutive characters
$                   # end of string

will do this. But this won't look nice (or easily maintainable) in JavaScript:

if (/^(?=.{6,15}$)(?=.*[A-Za-z])(?=.*[0-9])(?:(.)(?!\1\1))*$/.test(subject)) {
    // Successful match
} else {
    // Match attempt failed
}
Tim Pietzcker
Exactly what I have looked for.. Thanks a lot.
SLM