Skip to content

Username rules

Rodrigo Contreras edited this page Feb 16, 2019 · 1 revision

We want to create a regular expression to validate usernames against these criteria:

  • Only contains alphanumeric characters, underscore and dot.
  • Underscore and dot can't be at the end or start of a username (e.g username / username / .username / username.).
  • Underscore and dot can't be next to each other (e.g user_.name).
  • Underscore or dot can't be used multiple times in a row (e.g user__name / user..name).
  • Number of characters must be between 3 to 20.

The proper regex would be:

^(?=.{3,20}$)(?![_.-])(?!.*[_.-]{2})[a-zA-Z0-9._-]+(?<![_.-])$

But while this answer is valid for most languages and engines, not all support negative lookahead and lookbehind zero-length assertions.

So we are going to use:

^[a-zA-Z]+([_.-]?[a-zA-Z0-9])*$

And check the length in code.

The testing playground was this:

rodrigo.cr
rodri.con.r
rodrigo_cr
rodrigo-cr
rodri-con_r
rod_23
23124
r12343
rock134-
rambo.
.ro
-rocky12
ro..r
ro-.ck
ro_1_ck
r0ck
user1294594
ⓡⓞⓒⓚⓨ
ⱤØ₵₭Ɏ
я๏ȼЌ¥
尺のᄃズリ
rao-d-r-i-g-o-o-d-r-i
r-o-d-r-i-g-o-o-d-r-i
c-o-n-t-r-e-r-rodrigo
rodrigo-c-o-n-t-r-e-r-a-s-r-e-y-e-s
rodrigo.c.o.n.t.r.e.r.a.s.r.e.y.e.s
rodrigo-c-o-n-t-r-e-r-a-s-r-e-y-ess
rodrigocontrerasreyes
rodrigocontrerasreyesnombrelargo
r
ro
rod
rodri
1
123
123a
Clone this wiki locally