Asp.Net Core 数据校验(DataAnnotations,FluentValidation)
1.Asp.Net Core 数据校验(DataAnnotations,FluentValidation)
1.1 DataAnnotations
.NET Core中内置了对数据校验的支持,System.ComponentModel.DataAnnotations
- [Required]
- [EmailAddress]
- [RegularExpression]
- [[Phone]]
- CustomValidationAttribute
- IValidatableObject
添加用户的接口
请求参数验证
1.2 FluentValidation
FluentValidation:用类似于EF Core中Fluent API的方式进行校验规则的配置,也就是我们可以把对模型类的校验放到单独的校验类中。
(1)Install-Package FluentValidation.AspNetCore
(2)注入FluentValidation
builder.Services.AddFluentValidation(fv => {
Assembly assembly = Assembly.GetExecutingAssembly();
fv.RegisterValidatorsFromAssembly(assembly);// RegisterValidatorsFromAssemblies
});
(3) AbstractValidator<>
public class CreateUserRequestValidator : AbstractValidator<CreateUserRequest>
{
public CreateUserRequestValidator(UserManager<User> userManager)
{
//用户名
RuleFor(x => x.UserName).NotNull()
//异步
//.MustAsync(async (name,_) => (await userManager.Users.LongCountAsync<User>(u => u.UserName == name)) == 0)
.Must(name => userManager.Users.LongCount<User>(u => u.UserName == name) == 0)
.WithMessage(c => $"用户名{c.UserName}已经存在");
//密码
RuleFor(x => x.Password).NotNull().Length(3, 10)
.WithMessage("密码长度必须介于3到10之间")
.Equal(x => x.ConfimPassword)
.WithMessage("两次密码必须一致");
//邮箱
RuleFor(x => x.Email).NotNull().EmailAddress()
.WithMessage("邮箱格式不正确");
//电话
RuleFor(x => x.PhoneNumber).NotNull()
.Must(IsPhone)
.WithMessage("电话必须是11位数字");
}
private bool IsPhone(string str)
{
var re = @"^1\d{10}$";//正则表达式
if (Regex.IsMatch(str, re))
{
return true;
}
return false;
}
}
(4)测试