我有一个FluentValidator,它有多个属性,如zip和county等.我想创建一个规则,它接受两个属性,就像RuleFor构造一样
public class FooArgs
{
public string Zip { get; set; }
public System.Guid CountyId { get; set; }
}
public class FooValidator : AbstractValidator<FooArgs>
{
RuleFor(m => m.CountyId).Must(ValidZipCounty).WithMessage("wrong Zip County");
}
Run Code Online (Sandbox Code Playgroud)
这有效,但我想将Zip和县都传递到rue以便验证.实现这一目标的最佳方法是什么?
bpr*_*ard 36
有一个Must重载也为您提供了此处FooArgs记录的对象.它允许您轻松地将两个参数传递到您的方法中,如下所示:
RuleFor(m => m.CountyId).Must((fooArgs, countyId) =>
ValidZipCounty(fooArgs.Zip, countyId))
.WithMessage("wrong Zip County");
Run Code Online (Sandbox Code Playgroud)
小智 15
刚刚遇到这个老问题,我想我有一个更简单的答案.您可以轻松地通过你的整个对象到自定义的验证规则通过简化参数RuleFor,例如
RuleFor(m => m).Must(fooArgs =>
ValidZipCounty(fooArgs.Zip, fooArgs.countyId))
.WithMessage("wrong Zip County");
Run Code Online (Sandbox Code Playgroud)
如果该ValidZipCountry方法对于验证器是本地的,并且您可以将其签名更改为a,FooArgs那么代码将简化为
RuleFor(m => m).Must(ValidZipCounty).WithMessage("wrong Zip County");
Run Code Online (Sandbox Code Playgroud)
唯一的缺点是PropertyName结果验证错误将是一个空字符串.这可能会导致验证显示代码的问题.但是,错误属于哪个属性并不是很清楚,ContryId或者Zip,这确实有意义.
小智 10
关于什么:
RuleFor(m => new {m.CountyId, m.Zip}).Must(x => ValidZipCounty(x.Zip, x.CountyId))
.WithMessage("wrong Zip County");
Run Code Online (Sandbox Code Playgroud)
就我而言,x.RequiredProperty如果另一个属性不为空(在下面的示例中),我需要将一个属性标记为必需(x.ParentProperty在下面的示例中)。我最终使用了When语法:
RuleFor(x => x.RequiredProperty).NotEmpty().When(x => x.ParentProperty != null);
Run Code Online (Sandbox Code Playgroud)
或者,如果您对一个常见的 when 子句有多个规则,您可以将其编写如下:
RuleFor(x => x.RequiredProperty).NotEmpty().When(x => x.ParentProperty != null);
Run Code Online (Sandbox Code Playgroud)
语法的定义When如下:
When(x => x.ParentProperty != null, () =>
{
RuleFor(x => x.RequiredProperty).NotEmpty();
RuleFor(x => x.OtherRequiredProperty).NotEmpty();
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15494 次 |
| 最近记录: |