I have created a datechecker class, which returns an error if the selected date is in the past:
public class ValidateDateRange : ValidationAttribute
{
public DateTime FirstDate = DateTime.Today;
//public DateTime SecondDate { get; set; }
private const string DefaultIncorrectDateMessage = "The date you entered is incorrect. Please try again";
public string DateInPastMessage { get; set; }
//public string DateNotInRangeMessage { get; set; }
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
// your validation logic
if (Convert.ToDateTime(value) >= DateTime.Today)
{
return ValidationResult.Success;
}
else
{
return new ValidationResult(DateInPastMessage ?? DefaultIncorrectDateMessage);
}
}
}
This is my view:
[ValidateDateRange(DateInPastMessage = "Your date is in the past. Please select a date starting from today!")]
[DataType(DataType.Date)]
public DateTime ArrivalDate { get; set; }
This works correctly, however the DateInPastMessage
is now returned as a debug message, when the application fails on db.SaveChanges().
I want to have this message in the View, like a normal error message:
How can I send my custom error message to the View? Can this be done without creating custom jquery validation in every view where I have a datepicker field?