Custom Validation is very useful when we are using the same property in a number of places in our application. Rather than adding AddModelError in ModelState, it is a good practice to create this in a separate reusable library so that we can use this in the project with a very consistent method and re-use in any other project. This should be a project independent library and reusable component.
Following are the steps to create Custom Validator and use it in view model classes.
- Create new class DateRangeAttribute inherit from ValidationAttribute
- Ensure value is of type DateTime, if not throw ValidationException.
- Create constructor to get values dynamically from the View Model.
- Override IsValid method of ValidationAttribute class and write logic to validate Date range.
Example
Date Range Attribute Class
- public class DateRangeAttribute: ValidationAttribute
-
- {
-
- private int _endAge;
-
- private int _startAge;
-
- public DateRangeAttribute(int startAge, int endAge)
-
- {
-
- startAge = _startAge;
-
- endAge = _endAge;
-
- }
-
- protected override ValidationResult IsValid(object value, ValidationContext validationContext)
-
- {
-
- if (!(value is DateTime))
-
- {
-
- throw new ValidationException("DateRange is valid for DateTime property only.");
-
- } else
-
- {
-
- var date = (DateTime) value;
-
-
-
- if ((Calculate.GetAge(date) < _startAge) || (Calculate.GetAge(date) < _endAge))
-
- {
-
- return new ValidationResult(this.FormatErrorMessage(validationContext.MemberName));
-
- } else
-
- {
-
- return ValidationResult.Success;
-
- }
-
- }
-
- }
-
- }
Usage:
- public class User
-
- {
- [Required]
-
- public string FirstName
- {
- get;
- set;
- }
-
- [Required]
-
- public string LastName
- {
- get;
- set;
- }
-
- [DateRange(18, 100)]
-
- public string BirthDate
- {
- get;
- set;
- }
-
- }