So I have this issue.
I have 2 field is Date of birth
and Start working date
.I want to apply custom validation following this if
start working date - date of birth is >= 22
then is valid.So here is my code
[AttributeUsage(AttributeTargets.Property)]
public class MiniumAgeAttribute:ValidationAttribute
{
private DateTime dob { get; set; }
private DateTime startDate { get; set; }
public MiniumAgeAttribute(DateTime DOB, DateTime StartDate)
{
dob = DOB;
startDate = StartDate;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
int age;
age = startDate.Year - dob.Year;
if (age >= 22)
{
return ValidationResult.Success;
}
else
{
return new ValidationResult("Age is required to be 22 or more");
}
}
}
But when I apply my validation rules in model I get this error
So how can I fix it. Kind Regard.
Attributes are metadata and must be known at compile time and therefore must be constants. You cannot pass the value of a property which is not know until runtime. Instead, you pass the name of the property and use reflection to get the value of the property.
Typically you decorate a model property with the attribute so its only necessary to pass the name of the other property, not both
dob
andstartDate
. In additional your attribute allows no flexibility because you have hard coded the age in the method, and that value should also be passed to the method so that it can be used as (say)You logic is also incorrect because
startDate.Year - dob.Year
does not take into account the day and month values of the dates.Your attribute should be
You can also enhance this further by implementing
IClientValidatable
and adding scripts to the view to give you client side validation using thejquery.validate.js
andjquery.validate.unobtrusive.js
plugins. For more detail, refer THE COMPLETE GUIDE TO VALIDATION IN ASP.NET MVC 3 - PART 2