Sli*_*nky 26 c# fluentvalidation asp.net-mvc-3
我正在尝试包含复杂视图模型的项目的FluentValidation,我在这里阅读文档,但我没有看到如何设置规则来验证在我的视图模型中声明的对象列表.在下面的示例中,视图模型中的列表包含一个或多个Guitar对象.谢谢
查看模型
[FluentValidation.Attributes.Validator(typeof(CustomerViewModelValidator))]
public class CustomerViewModel
{
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Display(Name = "Phone")]
public string Phone { get; set; }
[Display(Name = "Email")]
public string EmailAddress { get; set; }
public List<Guitar> Guitars { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
View Model中使用的吉他类
public class Guitar
{
public string Make { get; set; }
public string Model { get; set; }
public int? ProductionYear { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
查看模型验证器类
public class CustomerViewModelValidator : AbstractValidator<CustomerViewModel>
{
public CustomerViewModelValidator()
{
RuleFor(x => x.FirstName).NotNull();
RuleFor(x => x.LastName).NotNull();
RuleFor(x => x.Phone).NotNull();
RuleFor(x => x.EmailAddress).NotNull();
//Expects an indexed list of Guitars here????
}
}
Run Code Online (Sandbox Code Playgroud)
小智 49
您可以将其添加到CustomerViewModelValidator
RuleFor(x => x.Guitars).SetCollectionValidator(new GuitarValidator());
Run Code Online (Sandbox Code Playgroud)
所以你的CustomerViewModelValidator看起来像这样:
public class CustomerViewModelValidator : AbstractValidator<CustomerViewModel>
{
public CustomerViewModelValidator()
{
RuleFor(x => x.FirstName).NotNull();
RuleFor(x => x.LastName).NotNull();
RuleFor(x => x.Phone).NotNull();
RuleFor(x => x.EmailAddress).NotNull();
RuleFor(x => x.Guitars).SetCollectionValidator(new GuitarValidator());
}
}
Run Code Online (Sandbox Code Playgroud)
添加GuitarValidator看起来像:
public class GuitarValidator : AbstractValidator<Guitar>
{
public GuitarValidator()
{
// All your other validation rules for Guitar. eg.
RuleFor(x => x.Make).NotNull();
}
}
Run Code Online (Sandbox Code Playgroud)
小智 27
不推荐使用此代码: RuleFor(x => x.Guitars).SetCollectionValidator(new GuitarValidator());
这是新的:
RuleForEach(x => x.Guitars).SetValidator(new GuitarValidator());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18606 次 |
| 最近记录: |