public class Dinner
{
public string ID { get; set; }
public string Title { get; set; }
public Category Category { get; set; }
public DateTime? DateCreated { get; set; }
}
Model view for that class (important part) is
public class DinnerModelView
{
...
[UIHint("DatePicker")]
[DateTime(ErrorMessage = "Invalida date")]
public DateTime? DateCreated { get; set; }
}
Where DateTimeAttriburte is
public class DateTimeAttribute : ValidationAttribute
{
public DateTimeAttribute () : base (() => "Invalid date") { }
public DateTimeAttribute(string errorMessage) : base(() => errorMessage) { }
public override bool IsValid(object value)
{
if (value == null)
return true;
bool isValid = false;
if (value is DateTime)
isValid = true;
DateTime tmp;
if (value is String)
{
if(String.IsNullOrEmpty((string)value))
isValid = true;
else
isValid = DateTime.TryParse((string)value, out tmp);
}
return isValid;
}
}
However model state error still says “The value ‘xxxx’ is not valid for DateCreated.”
I am not able to replace this message. WHY?
It seems as since the DateCreated property is of type DateTime then MVC will somehow validate it before checking your DateTimeAttribute and thereby never get to your custom error message.
If you change your DateCreated to string instead, it will probably work. But since you will have to save the value to your database, you wouldn’t want to change the DateCreated type. So instead you can create a new property called DateCreatedStr and let the user type data into this property instead. And just before saving your data, you can move your (validated) data from DateCreatedStr to DateCreated.
I know it is not a nice way to do it, but it works!