This article is to help us, how to
implement custom validation and use it as Data Annotation.
Custom Validation is very useful when we
are using the same Property in number of places in our application, rather than
to add AddModelError in ModelState,
it is a good practice to create this in a separate reusable library so that we
can use this in project with very consistent way and re-use in any other project.
This should be 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;
//Better
to create DateTime extension method to calculate Age
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; }
}
Good going sir ji
ReplyDeleteThanks buddy
DeleteAwesome! keep it up.
ReplyDelete