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
use this pattern
^(?=.*[a-zA-Z])[a-zA-Z -]+$
oh, for alphanumeric use
^(?=.*[a-zA-Z0-9])[a-zA-Z 0-9-]+$
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 [az]+
matches one or more letters [ -]?[az]+
matches an optional single space or dash followed by letters... (?:[ -]?[az]+)*
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]+)*$
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.