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");
});
}
}
I am trying to validate the list of child based on the parent model property value.
I need to validate the common rules and also specific ruleset of ALL the childs from the parent. I tried the below code RuleFor(x => x.ChildList).SetCollectionValidator(new ChildClassValidator().Validate(new ChildClass(), "ParentId1"));
in parent validator but is not allowed
I went through Child Model Validation using Parent Model Values. Fluent Validation. MVC4 but it is for only one property.