I am having trouble specifying the error message for the validation of a DateTime input value using data annotations in my model. I would really like to use the proper DateT
I have one dirty solution.
Create custom model binder:
public class CustomModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if(value != null && !String.IsNullOrEmpty(value.AttemptedValue))
{
T temp = default(T);
try
{
temp = ( T )TypeDescriptor.GetConverter(typeof(T)).ConvertFromString(value.AttemptedValue);
}
catch
{
bindingContext.ModelState.AddModelError(bindingContext.ModelName, "A valid Date or Date and Time must be entered eg. January 1, 2014 12:00AM");
bindingContext.ModelState.SetModelValue(bindingContext.ModelName, value);
}
return temp;
}
return base.BindModel(controllerContext, bindingContext);
}
}
And then in Global.asax.cs:
protected void Application_Start()
{
//...
ModelBinders.Binders.Add(typeof(DateTime), new CustomModelBinder());