I have a number of form fields, such as phone numbers and postal codes, which can be left empty. However, when they are filled out, I want them to conform to strict formatting rules.
I am looking to employ Fluent Validation for this task, but I have yet to find anything which can do the following:
RuleFor(x => x.PhoneNumber)
.Matches(@"^\d{3}-\d{3}-\d{4}$")
.When(x => x.PhoneNumber.Length != 0)
.WithMessage("Phone number must be a valid 10-digit phone number with dashes, in the form of “123-456-7890”")
.Length(12, 12).When(x => x.PhoneNumber.Length >= 1).WithMessage("Phone number must be in the form of “123-456-7890”");
Right now both of these throw a “Object reference not set to an instance of an object.” error.
Am I making any sense, or is this not even possible with FluentValidation?