【问题标题】:Return multiple validation failures from a single Custom() rule?从单个 Custom() 规则返回多个验证失败?
【发布时间】:2018-02-06 14:37:43
【问题描述】:

使用 FluentValidation 和 Custom() 规则,我希望能够验证子对象的集合,并为每个无效的子对象返回 ValidationFailure

我不能使用集合验证器,因为子对象不包含执行规则的正确信息 - 它必须在父对象的上下文中运行。

但是 Custom() API 限制我返回单个 ValidationFailure 或什么都不返回。

我可以使用一种模式来允许单个规则生成多个错误吗?

【问题讨论】:

  • 我也达到了这一点。有什么解决办法吗?

标签: fluentvalidation


【解决方案1】:

我找到了一个很好的解决方案 - 将 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;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-30
    • 1970-01-01
    • 2019-01-19
    • 1970-01-01
    • 1970-01-01
    • 2016-07-06
    • 2016-08-24
    • 1970-01-01
    相关资源
    最近更新 更多