Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to valid DateofBirth using fluent Validation in C# if it exceeds current year?
FluentValidation in C# provides a powerful way to validate model properties using a fluent interface. When validating date of birth, you need to ensure the date doesn't exceed the current year and falls within a reasonable age range.
This validation is essential for preventing future dates in birth date fields and ensuring data integrity in applications dealing with user registration or profile management.
Syntax
Following is the syntax for creating a date of birth validation rule using FluentValidation −
RuleFor(p => p.DateOfBirth)
.Must(BeAValidAge)
.WithMessage("Invalid {PropertyName}");
Following is the syntax for running the validator −
ValidationResult results = validator.Validate(person);
Key Components
RuleFor − Specifies which property to validate using a lambda expression.
Must − Defines a custom validation condition that must return true.
WithMessage − Specifies the error message when validation fails.
ValidationResult − Contains validation results with
IsValidboolean andErrorscollection.
Using Custom Validation Method
The following example demonstrates how to validate date of birth to ensure it doesn't exceed the current year and falls within a reasonable age range −
using System;
using System.Collections.Generic;
using FluentValidation;
using FluentValidation.Results;
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<PersonModel> {
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;
}
}
class Program {
static void Main(string[] args) {
List<string> errors = new List<string>();
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);
}
}
}
The output of the above code is −
Invalid Date Of Birth
Using Built-in Date Range Validation
FluentValidation also provides built-in methods for date range validation −
using System;
using System.Collections.Generic;
using FluentValidation;
using FluentValidation.Results;
public class PersonModel {
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
}
public class PersonValidator : AbstractValidator<PersonModel> {
public PersonValidator() {
RuleFor(p => p.DateOfBirth)
.LessThan(DateTime.Today)
.WithMessage("Date of birth cannot be in the future")
.GreaterThan(DateTime.Today.AddYears(-120))
.WithMessage("Date of birth cannot be more than 120 years ago");
}
}
class Program {
static void Main(string[] args) {
PersonModel person = new PersonModel {
FirstName = "John",
LastName = "Doe",
DateOfBirth = DateTime.Today.AddDays(10)
};
PersonValidator validator = new PersonValidator();
ValidationResult results = validator.Validate(person);
if (!results.IsValid) {
foreach (var error in results.Errors) {
Console.WriteLine(error.ErrorMessage);
}
} else {
Console.WriteLine("Validation passed!");
}
}
}
The output of the above code is −
Date of birth cannot be in the future
Validation Result Properties
| Property | Type | Description |
|---|---|---|
| IsValid | bool | Returns true if validation succeeded, false otherwise |
| Errors | IList<ValidationFailure> | Collection containing details about validation failures |
Conclusion
FluentValidation provides flexible options for validating date of birth fields in C#. You can use custom validation methods with Must() or built-in methods like LessThan() and GreaterThan() to ensure dates don't exceed the current year and fall within acceptable ranges.
