多个字段的 NotEmpty 验证
NotEmpty Validation for Multiple Fields
我有一个包含一些 NotEmpty 字段的表单。现在我总是可以为每个字段编写规则并为每个字段编写相同的消息。我希望有更好的方法来编写它。也许把它写在一行中并列出所有字段。
我已经尝试了下面的代码,但它似乎并没有 work.I 我什至不确定这是否接近答案。我到处搜索,但似乎找不到示例。我也看过文档,没有运气。很抱歉,如果答案很明显,过去一个小时我一直在思考这个问题。
RuleFor(x => new { x.FirstField, x.SecondField, x.ThirdField, x.FourthField }).NotEmpty().WithMessage("Field cannot be null");
图书馆不允许这样做。但是正如 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"));
}
}
我有一个包含一些 NotEmpty 字段的表单。现在我总是可以为每个字段编写规则并为每个字段编写相同的消息。我希望有更好的方法来编写它。也许把它写在一行中并列出所有字段。
我已经尝试了下面的代码,但它似乎并没有 work.I 我什至不确定这是否接近答案。我到处搜索,但似乎找不到示例。我也看过文档,没有运气。很抱歉,如果答案很明显,过去一个小时我一直在思考这个问题。
RuleFor(x => new { x.FirstField, x.SecondField, x.ThirdField, x.FourthField }).NotEmpty().WithMessage("Field cannot be null");
图书馆不允许这样做。但是正如 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"));
}
}