【发布时间】:2016-03-22 06:17:07
【问题描述】:
想知道是否有可能避免为需要验证的每个字段编写规则,例如,除了Remarks 之外的所有属性都必须经过验证。我正在考虑避免为每个属性写RuleFor。
public class CustomerDto
{
public int CustomerId { get; set; } //mandatory
public string CustomerName { get; set; } //mandatory
public DateTime DateOfBirth { get; set; } //mandatory
public decimal Salary { get; set; } //mandatory
public string Remarks { get; set; } //optional
}
public class CustomerValidator : AbstractValidator<CustomerDto>
{
public CustomerValidator()
{
RuleFor(x => x.CustomerId).NotEmpty();
RuleFor(x => x.CustomerName).NotEmpty();
RuleFor(x => x.DateOfBirth).NotEmpty();
RuleFor(x => x.Salary).NotEmpty();
}
}
【问题讨论】:
-
当然可以,使用反射和/或属性可能是一个好的开始
-
所有属性的验证模式相同的频率如何?
-
@Domysee,你能分享一个例子吗?
-
@Dennis:我经常开始注意到系统中其他类的相同验证模式。所以,我想把这些东西自动化..
标签: c# .net fluentvalidation