I am using asp.net core 2.0 and I have a custom validation attribute for validating age.
public class ValidAgeAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var model = validationContext.ObjectInstance as FormModel;
var db = model.DOB.AddYears(100);
if (model == null)
throw new ArgumentException("Attribute not applied on Model");
if (model.DOB > DateTime.Now.Date)
return new ValidationResult($"{validationContext.DisplayName} can't be in future");
if (model.DOB > DateTime.Now.Date.AddYears(-16))
return new ValidationResult("You must be 17 years old.");
if (db < DateTime.Now.Date)
return new ValidationResult("We rescept you but we cannot accept this date. over 100 years old.");
return ValidationResult.Success;
}
}
but this attribute is dependent on my "FormModel" class which is my domain model class.
public class FormModel
{
[Required, Display(Name = "Date of Birth")]
[ValidAge]
[DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime DOB { get; set; }
}
I want this attribute not to depend on "FormModel" class as shown here.So can I somehow get the instance of the model on which I am using this attribute without having to hardcode model's name here ?