在ASP.NET MVC4中为无效的DateTime自定义错误消息MVC

Chr*_*cht 19 asp.net validation asp.net-mvc asp.net-mvc-4

我在使用模型中的数据注释指定验证DateTime输入值的错误消息时遇到问题.我真的想使用正确的DateTime验证器(而不是正则表达式等).

[DataType(DataType.DateTime, ErrorMessage = "A valid Date or Date and Time must be entered eg. January 1, 2014 12:00AM")]
public DateTime Date { get; set; }
Run Code Online (Sandbox Code Playgroud)

我仍然收到"字段日期必须是日期"的默认日期验证消息.

我错过了什么吗?

cil*_*ler 39

将以下键添加到Global.asax的Application_Start()中

ClientDataTypeModelValidatorProvider.ResourceClassKey = "YourResourceName";
DefaultModelBinder.ResourceClassKey = "YourResourceName";
Run Code Online (Sandbox Code Playgroud)

App_GlobalResources文件夹中创建YourResourceName.resx并添加以下键

  • FieldMustBeDate字段{0}必须是日期.
  • FieldMustBeNumeric字段{0}必须是数字.
  • PropertyValueInvalid值"{0}"对{1}无效.
  • PropertyValueRequired需要一个值.

  • 遗憾的是,这只适用于全球范围.对于单个领域,有没有办法做同样的事情? (3认同)
  • 当资源在单独的程序集中时,有没有办法实现这一点? (2认同)

小智 14

我找到了一个简单的解决方法.

你可以保持你的模型不受影响.

[DataType(DataType.Date)]
public DateTime Date { get; set; }
Run Code Online (Sandbox Code Playgroud)

然后覆盖视图中的"data-val-date"属性.

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

或者,如果要参数化消息,可以使用静态函数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))
})
Run Code Online (Sandbox Code Playgroud)

与资源类似:

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

  • 我会在这里避免所有的解决方案,但MVC团队创造了这个不幸的情况,对我来说这是最快/最简单的快速修复,即使我不喜欢它.遗憾的是,全球范围对我的项目不起作用.他们应该检查你是否已经放置了一个"DataType"数据注释并在这种情况下删除了它们的默认验证,而不是给你那个奇怪的错误:"不引人注目的客户端验证规则中的验证类型名称必须是唯一的.".这样,您就可以放置自己的消息了. (3认同)

x2.*_*x2. 9

我有一个脏的解决方案.

创建自定义模型绑定

public class CustomModelBinder<T> : 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在Global.asax.cs中:

protected void Application_Start()
{
    //...
    ModelBinders.Binders.Add(typeof(DateTime), new CustomModelBinder<DateTime>());
Run Code Online (Sandbox Code Playgroud)