user756659
user756659

Reputation: 3512

simple regex for name validation

Trying to do a simple name validation for an input field. I do not need a list on what fails and what passes.

What I am trying to do is :

The max doesn't appear to be working and it is failing on 0 and 1 character entered. I've always been bad with these as they don't come up much for me. Tried quite a few things.

/^([a-z]+[a-z '-.,]*){0,32}$/i

Upvotes: 0

Views: 2145

Answers (1)

The Guy with The Hat
The Guy with The Hat

Reputation: 11132

+ in regex means "repeat the previous character one or more times," * means "repeat the previous character zero or more times," and {0, 32} means "repeat the previous character zero to 32 times." Therefore ([a]+[b]*){0,32} repeats a repetition followed by a repetition.

I think the regex you want is

/^[a-z][a-z '-.,]{0,31}$|^$/i

Explanation here:

  • 1st Alternative: ^[a-z][a-z '-.,]{0,31}$
    • ^ assert position at start of the string
    • [a-z] match a single character present in the list below
      • a-z a single character in the range between a and z (case insensitive)
    • [a-z '-.,]{0,31} match a single character present in the list below
      • Quantifier: Between 0 and 31 times, as many times as possible, giving back as needed [greedy]
      • a-z a single character in the range between a and z (case insensitive)
      • <space> the literal character <space>
      • '-. a single character in the range between ' and .
      • , the literal character ,
    • $ assert position at end of the string
  • 2nd Alternative: ^$
    • ^ assert position at start of the string
    • $ assert position at end of the string

Upvotes: 2

Related Questions