首次失败时停止Fluent验证 [英] Stop Fluent Validation on first failure
问题描述
我正在为我的Request对象定义一个验证.
我希望验证器在第一个失败时停止,而不仅仅是在同一链上的失败者.
在下面的示例中,如果我的TechnicalHeader
对象为null,则当验证达到TechnicalHeader.MCUserid
的规则时,我会收到NullReference异常.
i'm defining a validation for my Request objects.
I would like the validator to stop on the very first failure, not only the one on the same chain.
In the example below, if my TechnicalHeader
object is null, i get a NullReference exception when the validation reaches the rule for TechnicalHeader.MCUserid
.
简而言之,我想根据第一个规则的结果对以下代码中的后三个规则进行条件验证
In poor words, i would like to do a conditional validation over the last three rules in the code below, according to the result of the first rule
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");
}
);
}
}
}
推荐答案
在使用When
条件运行依赖它们的规则之前,只需检查null
.
Just check for null
before running the rules that depend on them, using a When
condition.
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");
});
这篇关于首次失败时停止Fluent验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!