为所有出现的Rule()。NotEmpty();设置默认错误代码。

时间:2019-06-07 23:21:28

标签: c# fluentvalidation

我需要为每种相同类型的验证失败设置ErrorCode字段。

我们列出了API中发生错误时可能发送的应用程序错误列表。如何强制FluentValidation始终在ValidationFailure对象中返回特定的错误代码,而不必手动将.WithErrorCode(myErrorCode)

添加到每个规则中

现在,我必须一直执行以下操作。

RuleFor(x => x.SomeField).NotEmpty().WithErrorCode(errorCodes['EmptyField']);

我希望我可以进行全局设置,以对特定规则使用默认错误代码。

1 个答案:

答案 0 :(得分:0)

我建议为此编写自己的扩展方法:

public static class FluentValidationExtendions
{
    public static IRuleBuilderOptions<T, TProperty> NotEmptyWithDefaultCode<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder, string errorCode = null)
    {
        return ruleBuilder.NotEmpty().WithErrorCode(errorCode ?? errorCodes['EmptyField']);
    }
}

用法:

RuleFor(x => x.SomeField).NotEmptyWithDefaultCode();