public class Address
{
public string Home { get; set; }
public string Phone { get; set; }
}
public class Person
{
///
/// 姓名
///
public string Name { get; set; }
///
/// 年龄
///
public int Age { get; set; }
///
/// 性别
///
public bool Sex { get; set; }
///
/// 地址
///
public Address Address { get; set; }
}
紧接着创建实体的验证器
public class AddressValidator : AbstractValidator
{
public AddressValidator()
{
this.RuleFor(m => m.Home)
.NotEmpty()
.WithMessage("家庭住址不能为空");
this.RuleFor(m => m.Phone)
.NotEmpty()
.WithMessage("手机号码不能为空");
}
}
public class PersonValidator : AbstractValidator
{
public PersonValidator()
{
this.RuleFor(p => p.Name)
.NotEmpty()
.WithMessage("姓名不能为空");
this.RuleFor(p => p.Age)
.NotEmpty()
.WithMessage("年龄不能为空");
this.RuleFor(p => p.Address)
.SetValidator(new AddressValidator());
}
}
public class ValidatorHub
{
public AddressValidator AddressValidator { get; set; } = new AddressValidator();
public PersonValidator PersonValidator { get; set; } = new PersonValidator();
}