.net mvc验证有很多方式,NET自带的验证方式很难用,并且很复杂。让我们开发者感觉很不爽,今天我推荐一个第三方验证框架——FluentValidation(FluentValidation.MVC)真的很棒,你研究一下可以做深入开发。
首先我们通过Nuget 下载FluentValidation包, FluentValidation 以及FluentValidation.MVC5.然后建立两个实体,RegisterModel以及 LoginModel。
//登录实体
[Validator(typeof(LoginValidator))]
public class CustomerLoginModel: BaseModel
{
[AllowHtml]
public string LoginName { get; set; }
[AllowHtml]
[DataType(DataType.Password)]
public string LoginPassword { get; set; }
}
//注册实体
[Validator(typeof(RegisterValidator))]
public class CustomerRegisterModel : BaseModel
{
[AllowHtml]
public string LoginName { get; set; }
[AllowHtml]
public string Email { get; set; }
[DataType(DataType.Password)]
[AllowHtml]
public string Password { get; set; }
[DataType(DataType.Password)]
[AllowHtml]
public string ConfirmPassword { get; set; }
}
建立一个验证文件夹Validators,建立两个验证实体LoginValidator,RegisterValidator代码如下
/// <summary>
/// 注册验证
/// </summary>
public partial class RegisterValidator : AbstractValidator<CustomerRegisterModel>
{
public RegisterValidator()
{
//定义密码长度为3-10位
RuleFor(x => x.Password).NotEmpty().WithMessage("密码不能为空");
RuleFor(x => x.Password).Length(3, 10).WithMessage("密码长度为3-10位");
RuleFor(x => x.ConfirmPassword).NotEmpty().WithMessage("密码不能为空");
RuleFor(x => x.ConfirmPassword).Equal(x => x.Password).WithMessage("重复密码不正确");
RuleFor(x => x.Email).NotEmpty().WithMessage("邮箱不能为空");
RuleFor(x => x.Email).EmailAddress().WithMessage("邮箱格式不正确");
}
}
public partial class LoginValidator : AbstractValidator<CustomerLoginModel>
{
public LoginValidator()
{
//定义密码长度为3-10位
RuleFor(x => x.LoginPassword).NotEmpty().WithMessage("密码不能为空");
RuleFor(x => x.LoginName).NotEmpty().WithMessage("用户名不能为空");
RuleFor(x => x.LoginName).Length(3,10).WithMessage("登录名长度为3-10个长度");
}
}
这里可以自定义验证错误,例如手机号、邮箱、长度以及提示信息等等,精明的小伙伴会加入本地化资源来改善提示信息修改后造成的编译问题(通过本地化可以不通过编译来修改提示信息)。
登录的方法如下:
//登录
[HttpPost]
public ActionResult Index(CustomerLoginModel model)
{
LoginValidator validator = new LoginValidator();
ValidationResult result = validator.Validate(model);
//验证不通过的时候,把错误信息加入MVC内置的验证状态中
if (!result.IsValid)
{
result.Errors.ToList().ForEach(error =>
{
ModelState.AddModelError(error.PropertyName, error.ErrorMessage);
});
}
return View(model);
}
大家如果有什么疑问请加群 68848430 咨询。
资源下载地址:http://download.csdn.net/detail/hb12417058/9713569
扫一扫添加关注,更多精彩内容