[英]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.