Search code examples
c#regexfluentvalidation

Regex for including alphanumeric and special characters but not special characters on their own


Im trying to create some validation rules for a data member, but am having trouble with one of my regular expressions. Currently I am using @"[a-zA-Z']+$" as I want to allow strings such as:

  • John Smith (valid)
  • Steve Mc'millan (valid)
  • ''''' (invalid)
  • Hill St' (valid)

This works as expected, but when I try pass a string with just the special characters, it allows it. Is there a way where I can allow the special characters ', but not allow it on its own?

Here is my rule Im creating:

        RuleFor(h => h.Name)
            .Cascade(CascadeMode.Stop)
            .NotEmpty().WithMessage("{PropertyName} is required")
            .Matches(@"[a-zA-Z']+$").WithMessage("{PropertyName} is invalid");

Solution

  • You can use

    RuleFor(h => h.Name)
        .Cascade(CascadeMode.Stop)
        .NotEmpty().WithMessage("{PropertyName} is required")
        .Matches(@"^(?!'+$)[a-zA-Z']+(?:\s+[a-zA-Z']+)*$").WithMessage("{PropertyName} is invalid");
    

    See the regex demo.

    • ^ - matches the start of string position
    • (?!'+$) - a negative lookahead that fails the match if there are one or more ' chars followed by the end of string position immediately to the right of the current (i.e. start of string) position.
    • [a-zA-Z']+ - one or more letters or '
    • (?:\s+[a-zA-Z']+)* - zero or more repetitions of
      • \s+ - one or more whitespaces
      • [a-zA-Z']+ - one or more letters or ' chars
    • $ - end of string.