I have the following FluentValidation extension method for validating phone numbers:
public static IRuleBuilderOptions<T, string> MatchPhoneNumber<T>(this IRuleBuilder<T, string> rule)
=> rule.Matches(@"^(1-)?\d{3}-\d{3}-\d{4}$").WithMessage("Invalid phone number");
Which I call:
RuleFor(contact => contact.PhoneNumber).MatchPhoneNumber()
However, I only want the extension method to validate the phone number when the phone number string is not null/empty. I can do this by doing the following:
RuleFor(contact => contact.PhoneNumber)
.MatchPhoneNumber()
.When(contact => !string.IsNullOrEmpty(contact.PhoneNumber));
but is there a way I can do this in the extension method itself?