首页 > 解决方案 > 多个字段的 NotEmpty 验证

问题描述

我有一个带有一些 NotEmpty 字段的表单。现在我总是可以为每个字段编写规则并为每个字段编写相同的消息。我希望有更好的方法来编写它。也许将其写在一行中并列出所有字段。

我已经尝试了下面的代码,但它似乎不起作用。我什至不确定这是否接近答案。我到处搜索,但似乎找不到一个例子。我也看过文档,没有运气。抱歉,如果答案很明显,过去一个小时一直在困扰我。

RuleFor(x => new { x.FirstField, x.SecondField, x.ThirdField, x.FourthField }).NotEmpty().WithMessage("Field cannot be null");

标签: asp.net-mvcfluentvalidation

解决方案


图书馆不允许这样做。但正如 Roman 所说,您可以编写一个扩展,如下所示:

public class MyAbstractValidator<T> : AbstractValidator<T>
{
    public IEnumerable<IRuleBuilderInitial<T, TProperty>> RuleForParams<TProperty>(params Expression<Func<T, TProperty>>[] expressions)
    {
        return expressions.Select(RuleFor);
    }
}

public static class RuleBuilderInitialExtensions
{
    public static void ApplyForEach<T, TProperty>(this IEnumerable<IRuleBuilderInitial<T, TProperty>> ruleBuilders, Action<IRuleBuilderInitial<T, TProperty>> action)
    {
        foreach (var ruleBuilder in ruleBuilders)
        {
            action(ruleBuilder);
        }
    }
}

public class CustomerValidator : MyAbstractValidator<Customer>
{
    public CustomerValidator()
    {
        RuleForParams(x => x.FirstField, x => x.SecondField, x => x.ThirdField).ApplyForEach(x => x.NotEmpty().WithMessage("Field cannot be null"));
    }
}

推荐阅读