我正在尝试包含复杂视图模型的项目的FluentValidation,我读了documentation here但是我没有看到如何设置规则来验证在我的视图模型中声明的对象列表。在下面的示例中,视图模型中的列表包含一个或多个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; }
}
在View模型中使用的吉他类
public class Guitar
{
public string Make { get; set; }
public string Model { get; set; }
public int? ProductionYear { get; set; }
}
查看模型验证程序类
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????
}
}
答案 0 :(得分:40)
您可以将其添加到CustomerViewModelValidator
RuleFor(x => x.Guitars).SetCollectionValidator(new GuitarValidator());
所以你的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());
}
}
添加GuitarValidator看起来像:
public class GuitarValidator : AbstractValidator<Guitar>
{
public GuitarValidator()
{
// All your other validation rules for Guitar. eg.
RuleFor(x => x.Make).NotNull();
}
}
答案 1 :(得分:11)
此代码已弃用:RuleFor(x => x.Guitars).SetCollectionValidator(new GuitarValidator());
这是新的:
RuleForEach(x => x.Guitars).SetValidator(new GuitarValidator());
答案 2 :(得分:0)
RuleForEach(
itemToValidate =>
new YourObjectValidator());
public class YourObjectValidator : AbstractValidator<YourObject>
{
public EdgeAPIAddressValidator()
{
RuleFor(r => r.YourProperty)
.MaximumLenght(100);
}
}
答案 3 :(得分:0)
它与最新版本的Fluent兼容。
答案 4 :(得分:0)
它与最新版本的Fluent兼容 并包含要使用的完整示例。
答案中的代码已过时。