How to validate date of birth using fluent validation in C# if the date of birth exceeds the current year?

WBOY
Release: 2023-08-30 10:09:02
forward
826 people have browsed it

如果出生日期超过当前年份,如何使用 C# 中的流畅验证来验证出生日期?

To specify a validation rule for a specific attribute, call the RuleFor method, passing a lambda expression representing the attribute to be validated

RuleFor(p => p.DateOfBirth )

To run a validator, instantiate the validator object and call the Validate method, passing it the object to be validated.

ValidationResult results = validator.Validate(person);

The Validate method returns a ValidationResult object. It contains two properties

IsValid- a Boolean value indicating whether the validation was successful.

Errors- A collection of ValidationFailure objects containing details about any validation failures

Example 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; } }
Copy after login

Output

Invalid Date Of Birth
Copy after login

The above is the detailed content of How to validate date of birth using fluent validation in C# if the date of birth exceeds the current year?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!