I want to write a custom validator for my Web API project to check whether the input date is valid. Please find below the validator I wrote.
Validator:
public sealed class DateValidationAttribute : ValidationAttribute
{
public string DateString { get; set; }
public DateValidationAttribute(string dateString)
{
DateString = dateString;
}
public override string FormatErrorMessage(string name)
{
return string.Format(ErrorMessageString, name, DateString);
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var property = validationContext.ObjectType.GetProperty(DateString);
DateTime dateObject;
if (property != null && !DateTime.TryParse(value.ToString(), out dateObject))
{
return new ValidationResult(
FormatErrorMessage(validationContext.DisplayName)
);
}
return null;
}
}
Model:
public class TestModel
{
[DateValidation("DateOfBirth", ErrorMessage = "Date of birth is not a valid date")]
public DateTime? DateOfBirth { get; set; }
}
But if I input an invalid date, the value in the validator is coming as null (I assume its because of the model binding exception when it tries to convert value to a date). For valid dates I could see the value coming correctly. Also I can't give a null check in the validator as the model property is an optional field. I am not supposed to change the datatype of the field to "string"
Can any one help me to find an way to solve this retaining the data type DateTime?
Note: Please apologies me if there are mistakes in the question as I am a newbie to .NET technologies.