0
/(^[a-zA-Z]+-?[a-zA-Z0-9]+){5,15}$/g

regex criteria
match length must be between 6 and 16 characters inclusive
must start with a letter only
must contain letters, numbers and one optional hyphen
must not end with a hyphen

the above regular expression doesnt satisfy all 4 conditions. tried moving the ^ before the group and omitting the + quantifiers but doesnt work

glennsl
  • 28,186
  • 12
  • 57
  • 75
Ridhwaan Shakeel
  • 981
  • 1
  • 20
  • 39
  • What language ? –  Apr 22 '19 at 22:26
  • Well, at least my regex forces a number be present. –  Apr 22 '19 at 22:49
  • You should consider the security repercussions of limiting passwords. Please see [Reference - Password Validation](https://stackoverflow.com/q/48345922/3600709) for more information. The password length should not be capped at 16, your minimum password length should be increased at least to 8, and your password structure limitations should be reconsidered. – ctwheels Jun 19 '19 at 13:57

2 Answers2

1

You are setting the limiting quantifier on a group that already has quantified subpatterns, thus, the length restriction won't work.

To set the length restriction, add the (?=.{6,16}$) lookahead after ^ and then feel free to set your consuming pattern.

You may use

/^(?=.{6,16}$)[a-zA-Z][a-zA-Z0-9]*(?:-[a-zA-Z0-9]+)?$/

See the regex demo. Note you should not use g modifier when validating the whole input string against a regex.

Details

  • ^ - start of string
  • (?=.{6,16}$) - 6 to 16 chars in the string input allowed/required
  • [a-zA-Z] - a letter as the first char
  • [a-zA-Z0-9]* - 0+ alphanumeric chars
  • (?:-[a-zA-Z0-9]+)? - an optional sequence of - and then 1+ alphanumeric chars
  • $ - end of string.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
1

All you need

^(?i)(?=.{6,16}$)(?!.*-.*-)[a-z][a-z\d-]*\d[a-z\d-]*(?<!-)$

Readable

 ^ 
 (?i)
 (?= .{6,16} $ )               # 6 - 16 chars
 (?! .* - .* - )               # Not 2 dashes
 [a-z]                         # Start letter
 [a-z\d-]*                     # Optional letters, digits, dashes
 \d                            # Must be digit
 [a-z\d-]*                     # Optional letters, digits, dashes
 (?<! - )                      # Not end in dash
 $ 

Well, at least my regex forces a number be present.