To specify a validation rule for a specific attribute, call the RuleFor method, passing a lambda expression representing the attribute to be validated
To run a validator, instantiate the validator object and call the Validate method, passing it the object to be validated.
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
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
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!