[英]How to tell FluentValidation not to check rules for subfields of fields not included in the request?
我正在使用 FluentValidation 版本 9.2.2。 我收到以下消息:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
杰森:
{ "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");
问题是,如果我发送这样的 json:Json:
{ }
(没有地理信息),我收到一个 NullReferenceException,而我希望“GeographyInfo 丢失。预期:GeoInfo 类型的对象”。
发生的事情是我认为 FluentValidation 继续并检查第二条规则:在字段 x.Request.GeographyInfo.CountryCode 上,但在这种情况下我们没有 x.Request.GeographyInfo,因此进一步参考没有意义国家代码。
我如何告诉 FluentValidation 不要检查他找不到的字段子字段的规则? (不包括在请求中)
对于您的特定情况,您可以指示 FluentAPI 在第一次失败时跳过执行:
ValidatorOptions.CascadeMode = CascadeMode.StopOnFirstFailure;
或者,您可以使用 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.