好用的验证框架FluentValidation(下)
Install-Package FluentValidation.AspNetCore
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public string Tel { get; set; }
public string Email { get; set; }
public DateTime Birthday { get; set; }
public string IDCard { get; set; }
public PersonAddress Address { 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().NotEmpty();
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值必填!")
.NotEmpty()
.When(p => (DateTime.Now > p.Birthday.AddYears(1)))
.WithMessage(p => $"出生日期为{p.Birthday},现在时间为{DateTime.Now},大于一岁,CardID值必填!")
.Length(18)
.When(p => (DateTime.Now > p.Birthday.AddYears(1)));
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().NotEmpty();
RuleFor(a => a.Province).NotNull().NotEmpty();
RuleFor(a => a.City).NotNull().NotEmpty();
RuleFor(a => a.County).NotNull().NotEmpty();
RuleFor(a => a.Address).NotNull().NotEmpty();
RuleFor(a => a.Postcode).NotNull().NotEmpty().Length(6);
}
}
Starup.cs
public void ConfigureServices(IServiceCollection services)
{
services
.AddControllers()
.AddFluentValidation();
services.AddTransient<IValidator<Person>, PersonValidator>();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "FluentValidationWebDemo01", Version = "v1" });
});
}
[ApiController]
[Route("[controller]")]
public class HomeController : ControllerBase
{
private readonly ILogger<HomeController> _logger;
private readonly IValidator<Person> _validator;
public HomeController(ILogger<HomeController> logger, IValidator<Person> validator)
{
_validator = validator;
_logger = logger;
}
[HttpPost("/addperson")]
public IActionResult AddPerson([FromBody] Person person)
{
_logger.LogInformation("添加Person");
if (ModelState.IsValid)
{
return Ok("验证成功后,假装这里作了后端业务处理");
}
_logger.LogError("验证Person失败");
return BadRequest("person没有验证通过");
}
}
{
"id":0,
"birthday":"2021-03-29T07:00:18.061Z",
"idCard":"",
"name":"",
"email":"axzxs2001163.com",
"tel":"1345346714",
"address":{
"country":"中国",
"province":"山西",
"city":"",
"county":"古城",
"address":"",
"postcode":"04600"
}
}
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "00-21fffead3f693fdf9156d796baf4e4ef-a7d39f85acf57cff-00",
"errors": {
"Tel": [
"'Tel' 的格式不正确。"
],
"Name": [
"'Name' 不能为空。"
],
"Email": [
"'Email' 不是有效的电子邮件地址。"
],
"Address.City": [
"'City' 不能为空。"
],
"Address.Address": [
"'Address' 不能为空。"
],
"Address.Postcode": [
"'Postcode' 必须是 6 个字符,您输入了 5 字符。"
]
}
}
还是那句话,FluentValidation提供了更灵活,完强大的验证方式
.NET Core实战项目之CMS 第一章 入门篇-开篇及总体规划
【.NET Core微服务实战-统一身份认证】开篇及目录索引
Redis基本使用及百亿数据量中的使用技巧分享(附视频地址及观看指南)
.NET Core中的一个接口多种实现的依赖注入与动态选择看这篇就够了
用abp vNext快速开发Quartz.NET定时任务管理界面
评论