好用的验证框架FluentValidation(上)
把数据错误扼杀在早期,那就是在数据的入口处,一般数据都是打包成一个实体的方式进传递,FluentValidation就以实体类为单位进行属性验证的集合。
Install-Package FluentValidation
下面看一个例子吧。
实体类:
public class Person
{
public int Id { get; set; }
public DateTime Birthday { get; set; }
public string IDCard { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public PersonAddress Address { get; set; }
public string Tel { get; set; }
}
public class PersonAddress
{
public string Country { get; set; }
public string Province { get; set; }
public string City { get; set; }
public string County { get; set; }
public string Address { get; set; }
public string Postcode { get; set; }
}
验证实体类:
/// <summary>
/// Person验证
/// </summary>
public class PersonValidator : AbstractValidator<Person>
{
public PersonValidator()
{
RuleFor(p => p.Name).NotNull();
RuleFor(p => p.Email).NotNull().EmailAddress();
RuleFor(p => p.Birthday).NotNull();
RuleFor(p => p.IDCard)
.NotNull()
.When(p => (DateTime.Now > p.Birthday.AddYears(1)))
.WithMessage(p => $"出生日期为{p.Birthday},现在时间为{DateTime.Now},大于一岁,CardID值必填!");
RuleFor(p => p.Tel).NotNull().Matches(@"^(\d{3,4}-)?\d{6,8}$|^[1]+[3,4,5,8]+\d{9}$");
RuleFor(p => p.Address).NotNull();
RuleFor(p => p.Address).SetValidator(new PersonAddressValidator());
}
}
/// <summary>
/// Person Address验证
/// </summary>
public class PersonAddressValidator : AbstractValidator<PersonAddress>
{
public PersonAddressValidator()
{
RuleFor(a => a.Country).NotNull();
RuleFor(a => a.Province).NotNull();
RuleFor(a => a.City).NotNull();
RuleFor(a => a.County).NotNull();
RuleFor(a => a.Address).NotNull();
RuleFor(a => a.Postcode).NotNull().Length(6);
}
}
使用场景:
class Program
{
static void Main(string[] args)
{
var person = new Person()
{
//少一位
Tel = "1345346711",
Name = "桂素伟",
//格式错误
Email = "axzxs2001#163.com",
//设置生日,没有身份证
Birthday = DateTime.Parse("2020-03-28 00:00:00"),
Address = new PersonAddress()
{
//邮编位数不对
Postcode = "12345"
},
};
var validator = new PersonValidator();
var results = validator.Validate(person);
if (!results.IsValid)
{
foreach (var failure in results.Errors)
{
Console.WriteLine("属性 " + failure.PropertyName + " 验证失败:" + failure.ErrorMessage);
}
}
Console.WriteLine("--------------------------------------------------------------------");
Console.WriteLine(results.ToString("\r\n"));
}
}
FluentValidation有一个很赞的功能,就是验证某一属性时,可以用别的属性的值作为条件,组合实现验证,这样就能适应更多的业务逻辑验证场景。比如上例中的,只有大于一岁(Birthday)的人,身份证(IDCard)是必填项。当然FluentValidation不只这些功能,比如嵌套实体验证,组合验证规则等,都是很贴心的功能,期待大家尝试。
想要更快更方便的了解相关知识,可以关注微信公众号
****欢迎关注我的asp.net core系统课程****
《asp.net core精要讲解》 https://ke.qq.com/course/265696
《asp.net core 3.0》 https://ke.qq.com/course/437517
《asp.net core项目实战》 https://ke.qq.com/course/291868
《基于.net core微服务》 https://ke.qq.com/course/299524
《asp.net core精要讲解》 https://ke.qq.com/course/265696
《asp.net core 3.0》 https://ke.qq.com/course/437517
《asp.net core项目实战》 https://ke.qq.com/course/291868
《基于.net core微服务》 https://ke.qq.com/course/299524