SLM
SLM

Reputation: 849

Javascript RegEx Help

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

Upvotes: 2

Views: 1127

Answers (2)

Fabian
Fabian

Reputation: 13691

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

Upvotes: 2

Tim Pietzcker
Tim Pietzcker

Reputation: 336158

^                   # 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
}

Upvotes: 6

Related Questions