使用 FluentValidation 和Custom()规则,我希望能够验证子对象的集合,并ValidationFailure为每个无效的子对象返回 。
我无法使用集合验证器,因为子对象不包含执行规则的正确信息 - 它必须在父对象的上下文中运行。
然而,Custom()API 限制我只能返回一个ValidationFailure或根本不返回任何内容。
我可以使用一种模式来允许单个规则生成多个错误吗?
我找到了一个很好的解决方案 - 将 AddRule() 与 DelegateValidator 一起使用。
public MyValidator : AbstractValidator<MyClass>
{
public MyValidator()
{
AddRule(new DelegateValidator<MyClass>(MyRule));
}
private IEnumerable<ValidationFailure> MyRule(
MyClass instance,
ValidationContext<MyClass> context)
{
var result = new List<ValidationFailure>();
// add as many failures to the list as you want:
var message = "This is not a valid message";
result.Add(new ValidationFailure(nameof(MyClass.SomeProperty), message));
return result;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1163 次 |
| 最近记录: |