Olin Kirkland Olin Kirkland - 1 year ago 88
Javascript Question

Difficult regular expression for name validation

I'm trying to write a regular expression to check whether or not a proposed name is valid in a gaming platform.


  • Name must contain at least 3 and no more than 20 letters

  • Name must start with a uppercaseletter

  • Name must never have two uppercase letters in a row

  • Spaces are allowed, but must be preceded by a letter and be followed by an uppercase letter

  • Hyphens are allowed, but must be preceded by a letter and be followed by a lowercase letter

  • All uppercase letters must be followed by a lowercase letter unless they are followed by a space or hyphen

I know I can check separately for the length of the string so the first rule is irrelevant, but I figured I'd list it for good measure.

Test cases (Pass):

  • Foo

  • Hello World

  • Hello-world

  • Bigsby Platt-slatt

Test cases (Fail):

  • foo

  • Hello world

  • Hello-World

  • 33333333333

What regular expression can I use to solve this? Is it reasonable to expect to do this using only regular expressions, or will the pattern need to be analyzed using a different method?


Answer Source

This is a possible regular expression:

(?!.*[A-Z]{2})(?!.*[^A-Za-z][ -])(?!.* ([^A-Z]|$))(?!.*-([^a-z]|$))^[A-Z].{2,19}$

See demo on regex101.com.


Several of the rules can be expressed as "cannot contain" kind of rules, and they are easy to implement with negative look-ahead ((?! ... )):

  • No two capitals in sequence:

  • No non-letter followed by either a space or hyphen:

    (?!.*[^A-Za-z][ -])
  • No space that is followed by a non-capital or end of string ($):

    (?!.* ([^A-Z]|$)
  • No hyphen followed by a non-lowercase or end of string:

  • Finally, the actual match is done with this: a capital followed by 2 - 19 characters:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download