mikeGear
mikeGear

Reputation: 79

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:

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");

Upvotes: 2

Views: 1233

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626861

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.

Upvotes: 1

Related Questions