简体   繁体   中英

How to tell FluentValidation not to check rules for subfields of fields not included in the request?

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM