Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fluent Validation - conditional validation of a potentially null value

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?

like image 450
René Kåbis Avatar asked Oct 19 '25 08:10

René Kåbis


1 Answers

I think that you are getting “Object reference not set to an instance of an object.” when trying evaluate the length PhoneNumber property when it's null. First you need to check that it's not null and only then apply all the other rules. In addition to that regular expression that you used in Matches(@"^\d{3}-\d{3}-\d{4}$") already includes the length validation so you can safely remove

.Length(12, 12).When(x => x.PhoneNumber.Length >= 1).WithMessage("Phone number must be in the form of “123-456-7890”");

If you remove the length rule, something like that should work:

When(x =>  x.PhoneNumber != null, 
   () => {
      RuleFor(x => x.PhoneNumber).Matches(@"^\d{3}-\d{3}-\d{4}$")
      .WithMessage("Phone number must be a valid 10-digit phone number with dashes, in the form of “123-456-7890”");           
 });
like image 163
Alex Art. Avatar answered Oct 22 '25 05:10

Alex Art.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!