在我的模型中使用数据注释为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; }
我仍然得到默认的日期验证消息“字段日期必须是日期”。
我是不是遗漏了什么?
发布于 2013-03-13 12:43:58
我有一个肮脏的解决方案。
创建自定义模型绑定器:
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>());
发布于 2014-10-03 07:07:05
我找到了一个简单的解决方法。
你可以让你的模型保持不变。
[DataType(DataType.Date)]
public DateTime Date { get; set; }
然后覆盖视图中的“data-val-date”属性。
@Html.TextBoxFor(model => model.Date, new
{
@class = "form-control",
data_val_date = "Custom error message."
})
或者,如果你想参数化你的消息,你可以只使用静态函数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))
})
与资源类似:
@Html.TextBoxFor(model => model.Date, new
{
@class = "form-control",
data_val_date = String.Format(Resources.ErrorMessages.Date,
Html.DisplayNameFor(model => model.Date))
})
发布于 2015-05-29 00:37:12
我在操作方法开始时修改了ModelState集合中的错误,从而解决了这个问题。如下所示:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult MyAction(MyModel model)
{
ModelState myFieldState = ModelState["MyField"];
DateTime value;
if (!DateTime.TryParse(myFieldState.Value.AttemptedValue, out value))
{
myFieldState.Errors.Clear();
myFieldState.Errors.Add("My custom error message");
}
if (ModelState.IsValid)
{
// Do stuff
}
else
{
return View(model);
}
}
https://stackoverflow.com/questions/15377131
复制相似问题