How to valid DateofBirth using fluent Validation in C# if it exceeds current year?



To specify a validation rule for a particular property, call the RuleFor method, passing a lambda expression that indicates the property that you wish to validate

RuleFor(p => p.DateOfBirth)

To run the validator, instantiate the validator object and call the Validate method, passing in the object to validate.

ValidationResult results = validator.Validate(person);

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

IsValid - a boolean that says whether the validation suceeded.

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
Updated on: 2020-11-25T11:44:03+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements