[RESOLVED]DateType validation is not being displayed

Hello there

I have myself a MVC 4 project and I’m trying to display a different validation error for a Nullable DateTime. this is my model

[DataType(DataType.DateTime, ErrorMessage = "Please enter a valid date (ex: 15/02/2014)")]
[Display(Name = "Follow up date")]
public virtual DateTime? FollowUpDate { get; set; }

When I submit my form with the data of "01022014" I get this error

The value '01022014' is not valid for Follow up date.

Any reason why my DateType validation error is not being shown?

I have fixed my problem, here is my solution

I created myself a IModelBinder like so

public class DateTimeModelBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var dateValue = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            if (dateValue == null)
                return null;

            var date = dateValue.AttemptedValue;

            if (String.IsNullOrEmpty(date))
                return null;

            bindingContext.ModelState.SetModelValue(bindingContext.ModelName, bindingContext.ValueProvider.GetValue(bindingContext.ModelName));
            try
            {
                return DateTime.Parse(date);
            }
            catch (Exception)
            {
                bindingContext.ModelState.AddModelError(bindingContext.ModelName, String.Format(""{0}" is an invalid date. Please enter a valid date (ex: 15/02/2014)", bindingContext.ModelName));
                return null;
            }
        }
    }

Then inside my Global.asax I delcared my modelbinder like so

    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            ModelBinders.Binders.Add(typeof(DateTime), new DateTimeModelBinder());
            ModelBinders.Binders.Add(typeof(DateTime?), new DateTimeModelBinder());
        }
    }

And now when I input a invalid date I get my custom error message :).

Hope this helps anyone else that is having this problem

I am not clear why that happens.

But you get it done as want, if take care in view. check bold part

  <div class="form-group">
            @Html.LabelFor(model => model.FollowUpDate, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.TextBoxFor(model => model.FollowUpDate)
                @Html.ValidationMessageFor(model => model.FollowUpDate,"Please enter a valid date (ex: 15/02/2014)")
            </div>
        </div>

Leave a Reply