jQuery validation does not work with RangeAttribute
, per Rick Anderson. This renders the selected solution incorrect if you're using ASP.NET MVC 5's built-in jQuery validation.
Instead, see the below code from this answer.
public class WithinSixYearsAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
value = (DateTime)value;
// This assumes inclusivity, i.e. exactly six years ago is okay
if (DateTime.Now.AddYears(-6).CompareTo(value) <= 0 && DateTime.Now.CompareTo(value) >= 0)
{
return ValidationResult.Success;
}
else
{
return new ValidationResult("Date must be within the last six years!");
}
}
}
And it's implemented like any other attribute.
[WithinSixYears]
public DateTime SixYearDate { get; set; }