Customize the Error Message MVC for an invalid DateTime in ASP.NET MVC4

后端 未结 5 1279
不知归路
不知归路 2020-12-23 15:20

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

5条回答
  •  执念已碎
    2020-12-23 15:29

    I found one simple workaround.

    You can leave your model untouched.

    [DataType(DataType.Date)]
    public DateTime Date { get; set; }
    

    Then override the 'data-val-date' attribute in a view.

    @Html.TextBoxFor(model => model.Date, new
    {
        @class = "form-control",
        data_val_date = "Custom error message."
    })
    

    Or if you want to parameterize your messages, you can just use static function String.Format:

    @Html.TextBoxFor(model => model.Date, new
    {
        @class = "form-control",
        data_val_date = String.Format("The field '{0}' must be a valid date.",  
                                        Html.DisplayNameFor(model => model.Date))
    })
    

    Similar with resources:

    @Html.TextBoxFor(model => model.Date, new
    {
        @class = "form-control",
        data_val_date = String.Format(Resources.ErrorMessages.Date,  
                                       Html.DisplayNameFor(model => model.Date))
    })
    

提交回复
热议问题