public class ParentClass
{
public int ParentId { get; set; }
public int ActivityId { get; set; }
public DateTime UpateDate { get; set; }
public IList<ChildClass> ChildList { get; set; }
}
public class ParentClassValidator : AbstractValidator<ParentClass>
{
public ParentClassValidator()
{
RuleFor(x => x.ParentId).NotEmpty().WithMessage("Parent Id cannot be empty");
When(x => x.ParentId == 1, () =>
{
RuleFor(x => x.ActivityId).NotEmpty().WithMessage("Activity To cannot be empty.");
RuleFor(x => x.ChildList).SetCollectionValidator(new ChildClassValidator().Validate(new ChildClass(), "ParentId1"));
});
}
}
public class ChildClass
{
public int ChildId { get; set; }
public DateTime DueDate { get; set; }
}
public class ChildClassValidator : AbstractValidator<ChildClass>
{
public ChildClassValidator()
{
RuleFor(x => x.ChildId).NotEmpty().WithMessage("Child Id cannot be empty");
RuleSet("ParentId1", () =>
{
RuleFor(x => x.DueDate).Must(date => date != default(DateTime)).WithMessage("Due date cannot be empty");
});
}
}
我正在尝试根据父模型属性值验证子列表。
我需要验证来自父级的所有子级的通用规则以及特定规则集。我在父验证程序中尝试了以下代码RuleFor(x => x.ChildList).SetCollectionValidator(new ChildClassValidator().Validate(new ChildClass(), "ParentId1"));
,但不允许
我经历了Child Model Validation using Parent Model Values. Fluent Validation. MVC4,但它只适用于一个属性。
答案 0 :(得分:0)
[Validator(typeof(ParentClassValidator))]
public class ParentClass
{
public int ParentId { get; set; }
public int ActivityId { get; set; }
public DateTime UpateDate { get; set; }
public IList<ChildClass> ChildList { get; set; }
}
public class ParentClassValidator : AbstractValidator<ParentClass>
{
public ParentClassValidator()
{
RuleFor(x => x.ParentId).NotEmpty().WithMessage("Parent Id cannot be empty");
When(x => x.ParentId == 1, () =>
{
RuleFor(x => x.ActivityId).NotEmpty().WithMessage("Activity To cannot be empty.");
});
}
public override ValidationResult Validate(ValidationContext<ParentClass> context)
{
RuleFor(x => x.ChildList).SetCollectionValidator(new ExtMobileTransactionDataValidator(context.InstanceToValidate));
return base.Validate(context);
}
}
public class ChildClass
{
public int ChildId { get; set; }
public DateTime DueDate { get; set; }
}
public class ChildClassValidator : AbstractValidator<ChildClass>
{
public ChildClassValidator(ParentClass parent)
{
RuleFor(x => x.ChildId).NotEmpty().WithMessage("Child Id cannot be empty");
if(parent.ParentId == 1)
{
RuleFor(x => x.DueDate).Must(date => date != default(DateTime)).WithMessage("Due date cannot be empty");
}
}
}
我能够通过覆盖Validate方法来实现它。
如果子类不会被单独验证,请记住删除子类的Validator属性,否则它将抛出&#34;没有定义无参数构造函数&#34;错误。