Search code examples
javascriptregexvalidationclient-side-validation

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


Solution

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