0

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:

enter image description here

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?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Forza
  • 1,619
  • 3
  • 28
  • 49
  • 1
    You need custom jQuery validation code, yes, but you can always load that into the view(s) via an external JS file, and even include it in your "jsval" bundle. – Chris Pratt Mar 16 '15 at 19:56
  • Have a look at this [previous SO post](http://stackoverflow.com/questions/5390403/datetime-date-and-hour-validation-with-data-annotation) – wooters Mar 16 '15 at 23:03

1 Answers1

0

You should set the ErrorMessage in ValidationAttribute. I think that's why it's not showing.

ErrorMessage = DefaultIncorrectDateMessage;
beautifulcoder
  • 10,832
  • 3
  • 19
  • 29