FluentValidation – validation包含Object列表的View Model
我正在尝试包含复杂视图模型的项目的FluentValidation,我在这里阅读文档,但我没有看到如何设置规则来validation在我的视图模型中声明的对象列表。 在下面的示例中,视图模型中的列表包含一个或多个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 Guitars { get; set; } }
View Model中使用的吉他类
public class Guitar { public string Make { get; set; } public string Model { get; set; } public int? ProductionYear { get; set; } }
查看模型validation器类
public class CustomerViewModelValidator : AbstractValidator { 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???? } }
您可以将其添加到CustomerViewModelValidator
RuleFor(x => x.Guitars).SetCollectionValidator(new GuitarValidator());
所以你的CustomerViewModelValidator看起来像这样:
public class CustomerViewModelValidator : AbstractValidator { 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()); } }
添加GuitarValidator看起来像:
public class GuitarValidator : AbstractValidator { public GuitarValidator() { // All your other validation rules for Guitar. eg. RuleFor(x => x.Make).NotNull(); } }