0

I am using FluentValidation version 9.2.2. I am getting this following message:

System.NullReferenceException: 'Object reference not set to an instance of an object.'

Json:

{ "geographyInfo": { "CountryCode": "UK" } }

RuleFor(x => x.Request.GeographyInfo)
    .NotEmpty()
    .WithMessage("GeographyInfo missing. Expected: object of type GeoInfo.")
    .WithErrorCode("123")
    .WithName("geographyInfo");

RuleFor(x => x.Request.GeographyInfo.CountryCode)
    .NotEmpty()
    .WithMessage("Field geographyInfo.CountryCode is missing. Expected: 3 digit code")
    .WithErrorCode("13")
    .WithName("countryCode");

Problem is, if I send a json like this: Json:

{ }

(with no geo info), I am getting a NullReferenceException, while I expect the "GeographyInfo missing. Expected: object of type GeoInfo."

What happens is I think FluentValidation goes ahead and checks also the 2nd rule: on field x.Request.GeographyInfo.CountryCode, but we don't have x.Request.GeographyInfo in this case, so it doesn't make sense to further reference the CountryCode.

How do I tell FluentValidation not to check rules for subfields of fields he doesnt find? (not included in the request)

Sami
  • 393
  • 8
  • 22

1 Answers1

2

For your particular case you could instruct FluentAPI to skip execution on first failure:

ValidatorOptions.CascadeMode = CascadeMode.StopOnFirstFailure;

Alternatively, you could use When method to first check if object is null:

When(x => x.Request.GeographyInfo != null, () => {   
    RuleFor(x => x.Request.GeographyInfo.CountryCode)
      .NotEmpty()
      .WithMessage("Field geographyInfo.CountryCode is missing. Expected: 3 digit code")
      .WithErrorCode("13")
      .WithName("countryCode");
});
Nikita Chayka
  • 2,057
  • 8
  • 16
  • Thank you! RuleFor(x => x.Request.GeographyInfo?.CountryCode) - I tried this before, didn't work. I got: "An expression tree lambda may not contain a null propagating operator." // It's interesting that CascadeMode.StopOnFirstFailure; is a possibility, I am checking it now. I hope it doesn't interefere with other unrelated errors, for example an error on a completely different fields should ideally be shown in addition to the error on GeoInfo (main field, not subfields) – Sami Nov 02 '20 at 12:16
  • Oh yeah indeed, but you could then wrap RuleFor in When, as suggested here - https://stackoverflow.com/a/17095859/7064030 – Nikita Chayka Nov 02 '20 at 12:19