Asp.net

為 ASP.NET MVC4 中的無效 DateTime 自定義錯誤消息 MVC

  • March 13, 2013

我在使用模型中的數據註釋來指定驗證 DateTime 輸入值的錯誤消息時遇到問題。我真的很想使用正確的 DateTime 驗證器(而不是 Regex 等)。

[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; }

我仍然收到“欄位日期必須是日期”的預設日期驗證消息。

我錯過了什麼嗎?

我有一個骯髒的解決方案。

創建自定義模型綁定器:

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);
   }
}

然後在 Global.asax.cs 中:

protected void Application_Start()
{
   //...
   ModelBinders.Binders.Add(typeof(DateTime), new CustomModelBinder<DateTime>());

將以下鍵添加到 Global.asax 中的 Application_Start()

ClientDataTypeModelValidatorProvider.ResourceClassKey = "YourResourceName";
DefaultModelBinder.ResourceClassKey = "YourResourceName";

App_GlobalResources文件夾中創建YourResourceName.resx並添加以下鍵

  • FieldMustBeDate欄位 {0} 必須是日期。
  • FieldMustBeNumeric欄位 {0} 必須是數字。
  • PropertyValueInvalid值“{0}”對 {1} 無效。
  • PropertyValueRequired值是必需的。

引用自:https://stackoverflow.com/questions/15377131