简体   繁体   English

如何告诉 FluentValidation 不检查请求中未包含的字段的子字段的规则?

[英]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.我正在使用 FluentValidation 版本 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" } } { "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:问题是,如果我发送这样的 json:Json:

{ } { }

(with no geo info), I am getting a NullReferenceException, while I expect the "GeographyInfo missing. Expected: object of type GeoInfo." (没有地理信息),我收到一个 NullReferenceException,而我希望“GeographyInfo 丢失。预期: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.发生的事情是我认为 FluentValidation 继续并检查第二条规则:在字段 x.Request.GeographyInfo.CountryCode 上,但在这种情况下我们没有 x.Request.GeographyInfo,因此进一步参考没有意义国家代码。

How do I tell FluentValidation not to check rules for subfields of fields he doesnt find?我如何告诉 FluentValidation 不要检查他找不到的字段子字段的规则? (not included in the request) (不包括在请求中)

For your particular case you could instruct FluentAPI to skip execution on first failure:对于您的特定情况,您可以指示 FluentAPI 在第一次失败时跳过执行:

ValidatorOptions.CascadeMode = CascadeMode.StopOnFirstFailure;

Alternatively, you could use When method to first check if object is null:或者,您可以使用 When 方法首先检查对象是否为空:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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