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
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
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 stringYou mentioned alphanumeric
, so in case you also want to allow digits:
(?i)^[a-z0-9]+(?:[ -]?[a-z0-9]+)*$
use this pattern
^(?=.*[a-zA-Z])[a-zA-Z -]+$
oh, for alphanumeric use
^(?=.*[a-zA-Z0-9])[a-zA-Z 0-9-]+$