在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
认识Fluent Vaidation. 看到NopCommerce项目中用到这个组建是如此的简单,将数据验证从业务实体类中分离出来,真是一个天才的想法,后来才知道这个东西是一个开源的轻量级验证组建。 怎么使用: 业务实体类: 复制代码 代码如下: public class Person { public string NameField; public int Id { get; set; } public string Surname { get; set; } public string Forename { get; set; } public List<Person> Children { get; set; } public string[] NickNames { get; set; } public DateTime DateOfBirth { get; set; } public int? NullableInt { get; set; } public Person() { Children = new List<Person>(); Orders = new List<Order>(); } public int CalculateSalary() { return 20; } public Address Address { get; set; } public IList<Order> Orders { get; set; } public string Email { get; set; } public decimal Discount { get; set; } public double Age { get; set; } public int AnotherInt { get; set; } public string CreditCard { get; set; } public int? OtherNullableInt { get; set; } } public interface IAddress { string Line1 { get; set; } string Line2 { get; set; } string Town { get; set; } string County { get; set; } string Postcode { get; set; } Country Country { get; set; } } public class Address : IAddress { public string Line1 { get; set; } public string Line2 { get; set; } public string Town { get; set; } public string County { get; set; } public string Postcode { get; set; } public Country Country { get; set; } public int Id { get; set; } } public class Country { public string Name { get; set; } } public interface IOrder { decimal Amount { get; } } public class Order : IOrder { public string ProductName { get; set; } public decimal Amount { get; set; } } 对Person的指定验证规则: 复制代码 代码如下: using FluentValidation; public class CustomerValidator: AbstractValidator<Customer> { public CustomerValidator() { RuleFor(customer => customer.Surname).NotEmpty(); RuleFor(customer => customer.Forename).NotEmpty().WithMessage("Please specify a first name"); RuleFor(customer => customer.Discount).NotEqual(0).When(customer => customer.HasDiscount); RuleFor(customer => customer.Address).Length(20, 250); RuleFor(customer => customer.Postcode).Must(BeAValidPostcode).WithMessage("Please specify a valid postcode"); } private bool BeAValidPostcode(string postcode) { // custom postcode validating logic goes here } } // 手动验证规则 Customer customer = new Customer(); CustomerValidator validator = new CustomerValidator(); ValidationResult results = validator.Validate(customer); bool validationSucceeded = results.IsValid; IList<ValidationFailure> failures = results.Errors; Flent validation怎么与asp.net mvc验证库整合? 复制代码 代码如下: // 在Global.asax.cs中的Applicaton_Start()函数中注册为asp.net mvc默认的验证规则库。 // fluent validation FluentValidationModelValidatorProvider provider = new FluentValidationModelValidatorProvider(new AttributedValidatorFactory()); ModelValidatorProviders.Providers.Add(provider); DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false; 注意: 本文适合对.net以及MVC有所了解的读者,这里抛砖引玉,献丑了 |
请发表评论