luent Validation 翻译为:流畅验证
开源Codeplex其主页简介:该组件是一个轻量级的.NET类库,使用流畅的接口定义和lambda表达式为构建一个业务类的验证规则(A small validation library for .NET that uses a fluent interface and lambda expression for building validation rules for you business objects.)
将其应用到我们的项目中,首先新建一个业务实体类。注意需要引用 FluentValidation.dll 和 FluentValidation.Mvc;
[Validator(typeof(BankCardValidator))] public class BankCardModel { public string AccountCurrency { get; set; } /// <summary> /// 汇款单号 /// </summary> public string RemitOrderNo { get; set; } /// <summary> /// 汇款交易号 /// </summary> public string TradeNo { get; set; } /// <summary> /// 汇款人账户 /// </summary> public string RemittorAccount { get; set; } /// <summary> /// 汇款人姓名 /// </summary> public string RemittorName { get; set; } /// <summary> /// 汇款方式 /// </summary> public string RemitWay { get; set; } /// <summary> /// 汇款金额 /// </summary> public decimal RemitAmount { get; set; } }
然后是验证类
public class BankCardValidator : AbstractValidator<BankCardModel> { public BankCardValidator() { RuleFor(x => x.AccountCurrency).NotEmpty().WithMessage("请输入AccountCurrency"); RuleFor(x => x.RemitAmount).NotEmpty().WithMessage("请输入RemitAmount"); RuleFor(x => x.RemitOrderNo).NotEmpty().WithMessage("请输入RemitOrderNo"); RuleFor(x => x.RemittorName).NotEmpty().WithMessage("请输入RemittorName"); } }
如果需要在页面上使用,需要辅以 jquery.validate.min.js 和 jquery.validate.unobtrusive.js 两个js验证插件
由于其不是ASP.NET MVC的默认验证规则类库,我们就需要注册到ASP.NET MVC的验证规则库中
FluentValidationModelValidatorProvider provider = new FluentValidationModelValidatorProvider(new AttributedValidatorFactory()); ModelValidatorProviders.Providers.Add(provider); DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
最后出来的效果就是这样哒
本文引用自:https://www.jb51.net/article/57904.html