Validations are very important in any application and Validations restrict the invalid data being entered into the application.
In MVC we can build a custom validations framework by extending “ValidationAttribute”, “IClientValidatable”.
The “ValidationAttribute“ class serves as base class for all validations and By overriding “Isvalid” method we can extend the validations.
The ValidateAttribute take two parameters value and the Validation context which holds all the control values.
For example I want to compare two dates.
Create a class with extends the validation attribute and create a property of compare to date field name. using validation Context, retrieve the value the compare to date field value and then
Compare with Self value .
public class GreaterDateAttribute : ValidationAttribute
{
public string EarlierDateField { get; set; }
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
DateTime? date = value != null ? (DateTime?)value : null;
var earlierDateValue = validationContext.ObjectType.GetProperty(EarlierDateField)
.GetValue(validationContext.ObjectInstance, null);
DateTime? earlierDate = earlierDateValue != null ? (DateTime?)earlierDateValue : null;
if (date.HasValue && earlierDate.HasValue && date < earlierDate)
{
return new ValidationResult(ErrorMessage);
}
return ValidationResult.Success;
}
}
No comments:
Post a Comment