如果出生日期超过本年度,如何使用C#语言中的fluent验证有效?
要为特定属性指定验证规则,请调用RuleFor方法,并传递一个lambda表达式,该表达式指示您要验证的属性
RuleFor(p=>p.DateOfBirth)
要运行验证器,请实例化验证器对象并调用Validate方法,并传入该对象进行验证。
ValidationResultresults=validator.Validate(person);
Validate方法返回ValidationResult对象。这包含两个属性
IsValid-一个布尔值,表示是否验证成功。
错误-ValidationFailure对象的集合,其中包含有关任何验证失败的详细信息
例子1
static void Main(string[] args) { List errors = new List(); PersonModel person = new PersonModel(); person.FirstName = "TestUser"; person.LastName = "TestUser"; person.AccountBalance = 100; person.DateOfBirth = DateTime.Now.Date.AddYears(1); PersonValidator validator = new PersonValidator(); ValidationResult results = validator.Validate(person); if (results.IsValid == false) { foreach (ValidationFailure failure in results.Errors){ errors.Add(failure.ErrorMessage); } } foreach (var item in errors){ Console.WriteLine(item); } Console.ReadLine(); } } public class PersonModel { public string FirstName { get; set; } public string LastName { get; set; } public decimal AccountBalance { get; set; } public DateTime DateOfBirth { get; set; } } public class PersonValidator : AbstractValidator{ public PersonValidator(){ RuleFor(p => p.DateOfBirth) .Must(BeAValidAge).WithMessage("Invalid {PropertyName}"); } protected bool BeAValidAge(DateTime date){ int currentYear = DateTime.Now.Year; int dobYear = date.Year; if (dobYear <= currentYear && dobYear > (currentYear - 120)){ return true; } return false; } }
输出结果
Invalid Date Of Birth