asp.net-mvc - 多个字段的 NotEmpty 验证
问题描述
我有一个带有一些 NotEmpty 字段的表单。现在我总是可以为每个字段编写规则并为每个字段编写相同的消息。我希望有更好的方法来编写它。也许将其写在一行中并列出所有字段。
我已经尝试了下面的代码,但它似乎不起作用。我什至不确定这是否接近答案。我到处搜索,但似乎找不到一个例子。我也看过文档,没有运气。抱歉,如果答案很明显,过去一个小时一直在困扰我。
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"));
}
}
推荐阅读
- java - 如何在 ImageButton 中输入多个事件?
- javascript - 打开标签的链接
- php - 如何选择前100(表)然后限制显示
- matlab - 使用符号工具箱简化已知函数的表达式(例如三角函数)
- angular - 无法在 Angular 管道中将一个数组的值推入另一个数组
- c# - SlideMenuLayout 幻灯片不仅仅是布局,而是一个活动
- html - navbar 小于 navbar-brand
- python - 如何获取 lxml.etree._ElementTree 对象的父路径
- javascript - 在另一个组件上使用来自 ngFor 的信息
- python - 使用 scipy 在 python 中求解微分方程