使用FluentValidation来进行数据有效性验证
生活随笔
收集整理的這篇文章主要介紹了
使用FluentValidation来进行数据有效性验证
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
之前我介紹過了使用系統(tǒng)自帶的Data Annotations來進行數(shù)據(jù)有效性驗證,今天在CodePlex上逛的時候,發(fā)現(xiàn)了一個非常簡潔好用的庫:FluentValidation
由于非常簡潔,就直接拿官網(wǎng)的例子演示了:?
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;它還可以非常方便的與Asp.Net集成,用起來非常方便。官網(wǎng)的幫助文檔也非常詳盡,有數(shù)據(jù)有效性檢驗的朋友趕緊用起來把。
?
總結
以上是生活随笔為你收集整理的使用FluentValidation来进行数据有效性验证的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 基于Android系统开发的简易音乐播放
- 下一篇: MapReduce 计数器简介