-1

I want to make sure a first name field has at least one alphanumeric character and also allow spaces and dashes.

**VALID**

David
Billie Joe
Han-So

**INVALID**
-

Empty is also invalid
Adam Levitt
  • 9,676
  • 24
  • 77
  • 141

2 Answers2

3

To ensure the dashes and spaces happen in legitimate places, use this:

(?i)^[a-z]+(?:[ -]?[a-z]+)*$

See demo.

  • (?i) puts us in case-insensitive mode
  • ^ ensures we're at the beginning of the string
  • [a-z]+ matches one or more letters
  • [ -]?[a-z]+ matches an optional single space or dash followed by letters...
  • (?:[ -]?[a-z]+)* and this is allowed zero or more times
  • $ asserts that we have reached the end of the string

You mentioned alphanumeric, so in case you also want to allow digits:

(?i)^[a-z0-9]+(?:[ -]?[a-z0-9]+)*$
zx81
  • 38,175
  • 8
  • 76
  • 97
  • FYI added explanation. :) – zx81 Jun 22 '14 at 00:18
  • please modify your pattern to `(?i)^[a-z0-9]+(?:[ -][a-z0-9]+)*[a-z0-9]?$` to match at least "one" "alphanumeric" :-) – alpha bravo Jun 22 '14 at 00:21
  • @alphabravo The pattern already **did** match at least one alphanumeric character, since letters are alphanumeric. I didn't include digits in the character classes because I assumed Adam meant `alphabetical`, as suggested by his examples... But you're right that maybe he wants to include digits as well, so I added a second regex as an option. Thanks for pointing out that possibility. :) – zx81 Jun 22 '14 at 00:30
  • all joking aside, you are missing my point, you need to add the last `?` to match at least "ONE"!! – alpha bravo Jun 22 '14 at 00:33
  • @alphabravo I think I finally understood what you mean. You mean that the regex matched strings that were 2+ character long, but not single-letter strings? I have modified the expression, though not quite in the way you suggest. Good catch, thank you. :) – zx81 Jun 22 '14 at 00:46
  • @alphabravo Thanks for keeping me honest. :) – zx81 Jun 22 '14 at 00:49
1

use this pattern

^(?=.*[a-zA-Z])[a-zA-Z -]+$  

Demo

oh, for alphanumeric use

^(?=.*[a-zA-Z0-9])[a-zA-Z 0-9-]+$ 
alpha bravo
  • 7,292
  • 1
  • 14
  • 22