Home  >  Article  >  Backend Development  >  How to validate date of birth using fluent validation in C# if the date of birth exceeds the current year?

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

WBOY
WBOYforward
2023-08-30 10:09:02834browse

如果出生日期超过当前年份,如何使用 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;
   }
}

Output

Invalid Date Of Birth

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete