gpt4 book ai didi

validation - 第一次失败时停止 Fluent 验证

转载 作者:行者123 更新时间:2023-12-03 14:35:39 24 4
gpt4 key购买 nike

我正在为我的请求对象定义验证。
我希望验证器在第一次失败时停止,而不仅仅是同一链上的那个。
在下面的例子中,如果我的 TechnicalHeader对象为空,当验证达到 TechnicalHeader.MCUserid 的规则时,我收到 NullReference 异常.

简而言之,我想根据第一条规则的结果对下面代码中的最后三个规则进行条件验证

using System;
using ServiceStack.FluentValidation;
using MyProj.Services.Models;

namespace MyProj.Services.BaseService.Validators
{
public class BaseValidator<T> : AbstractValidator<T>
where T : RequestBase
{
public BaseValidator()
{
RuleSet(ServiceStack.ApplyTo.Put | ServiceStack.ApplyTo.Post,
() =>
{
this.CascadeMode = CascadeMode.StopOnFirstFailure;
RuleFor(x => x.TechnicalHeader).Cascade(CascadeMode.StopOnFirstFailure).NotNull().WithMessage("Header cannot be null");
RuleFor(x => x.TechnicalHeader).NotEmpty().WithMessage("Header cannot be null");
RuleFor(x => x.TechnicalHeader.Userid).NotEmpty().WithMessage("Userid cannot be null or an empty string");
RuleFor(x => x.TechnicalHeader.CabCode).GreaterThan(0).WithMessage("CabCode cannot be or less than 0");
RuleFor(x => x.TechnicalHeader.Ndg).NotEmpty().WithMessage("Ndg cannot be null or an empty string");
}
);
}
}
}

最佳答案

只需检查 null在运行依赖于它们的规则之前,使用 When健康)状况。

this.CascadeMode = CascadeMode.StopOnFirstFailure;
RuleFor(x => x.TechnicalHeader).NotNull().WithMessage("Header cannot be null");

// Ensure TechnicalHeader is provided
When(x => x.TechnicalHeader != null, () => {
RuleFor(x => x.TechnicalHeader.Userid).NotEmpty().WithMessage("Userid cannot be null or an empty string");
RuleFor(x => x.TechnicalHeader.CabCode).GreaterThan(0).WithMessage("CabCode cannot be or less than 0");
RuleFor(x => x.TechnicalHeader.Ndg).NotEmpty().WithMessage("Ndg cannot be null or an empty string");
});

关于validation - 第一次失败时停止 Fluent 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21605534/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com