public class Address
{
public string Address { get; set; }
public string City { get; set; }
}
public class AddressValidator : AbstractValidator<Address>
{
public AddressValidator()
{
RuleFor(x => x.Address).NotEmpty().WithMessage("The Address cannot be empty.");
RuleFor(x => x.City).NotEmpty().WithMessage("The City cannot be empty.");
}
}
public class PersonBase
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Address PermanentAddress { get; set; }
}
public class PersonGroupA : PersonBase
{
public int TotalSaleCount { get; set; }
}
public class PersonGroupB : PersonBase
{
public int TodaySaleCount { get; set; }
}
public class PersonBaseValidator : AbstractValidator<PersonBase>
{
public PersonBaseValidator()
{
RuleFor(x => x.FirstName).NotEmpty().WithMessage("The First Name cannot be empty.");
RuleFor(x => x.LastName).NotEmpty().WithMessage("The Last Name cannot be empty.");
RuleFor(x => x.PermanentAddress).SetValidator(new AddressValidator());
}
}
public class PersonGroupAValidator : AbstractValidator<PersonGroupA>
{
public PersonGroupAValidator()
{
RuleFor(x => x.TotalSaleCount).NotEmpty().WithMessage("The Total Sale Count cannot be empty.");
}
}
public class PersonGroupBValidator : AbstractValidator<PersonGroupB>
{
public PersonGroupBValidator()
{
RuleFor(x => x.TodaySaleCount).NotEmpty().WithMessage("The Today Sale Count cannot be empty.");
}
}
how to use base validator in child validator
This is working when add likebelow
public class PersonGroupAValidator : AbstractValidator<PersonGroupA> {
public PersonGroupAValidator() {
Include(new PersonBaseValidator());
RuleFor(x => x.TotalSaleCount).NotEmpty().WithMessage("The Total Sale Count cannot be empty.");
}
}