Search code examples
c#regexdata-annotations

Regular Expression for name validation containing A-Z a-z 0-9 apostrophe ' and dash -


I'm trying to validate names that contains A-Z a-z 0-9 apostrophe ' dash - and space.

0-9 apostrophe ' dash - and space are optional, but it should not allow only these optional stuffs without any alphabet.

For example, these should all match:

Jean-Paul
O'Donnel
Jay-Z
2Pac
Name with number in it like-> 50 Cent
Name with hyphen and number-> Rob2 ben-den1
Following should not match:
-'2571 (only 0-9 apostrophe ' dash - and space)
Empty String 
56757 (only number)

I've following Regex but it is not working for all above cases:

^[A-Za-z0-9][A-Za-z0-9\'\-]+([\ A-Za-z0-9][A-Za-z0-9\'\-]+)+$

Solution

  • You can use

    ^(?!(?:[ '-]?\d)+$)[A-Za-z0-9]+(?:[ '-][A-Za-z0-9]+)*$
    

    See the regex demo.

    Details:

    • ^ - start of string
    • (?!(?:[ '-]?\d)+$) - a negative lookahead that fails the match if there are one or more repetitions of an optional space/'/- and then a digit till end of string
    • [A-Za-z0-9]+ - one or more ASCII letters/digits
    • (?:[ '-][A-Za-z0-9]+)* - zero or more repetitions of a space/'/- and one or more ASCII letters/digits
    • $ - end of string.