DamirAlkhaov
DamirAlkhaov

Reputation: 23

problem with making preg_match for a username validating system

I made this regex code:

/^([a-zA-Z\d]+[_]?+[a-zA-Z\d]){3,12}$/

I want the expression to:

When I test a name with more than 12 chars it still gives me a positive result.

How do I fix this?

Upvotes: 2

Views: 56

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627082

You may use

^(?=.{3,12}$)[a-zA-Z\d]+(?:_[a-zA-Z\d]+)?$

Details

  • ^ - start of string
  • (?=.{3,12}$) - length allowed from 3 to 12 chars
  • [a-zA-Z\d]+ - 1+ letters or digits
  • (?:_[a-zA-Z\d]+)? - an optional sequence of _ and 1+ digits/digits
  • $ - end of string

Upvotes: 5

Related Questions