8

我有一个带有日期的 ASP.net MVC 模型:

public class EditModel
{ 
    [Display(Name="DOB")]
    public DateTime? DateOfBirth { get; set; }
}

@Html.TextBoxFor(m => m.DateOfBirth)
@Html.ValidationMessageFor(m => m.DateOfBirth)

当用户输入无效日期(例如 2011 年 9 月 31 日)时,错误消息如下所示:

The value '9/31/2011' is not valid for DOB.

当它尝试进行模型绑定并且不是我的验证之一时,就会发生这种情况。有没有办法自定义这个错误信息?我希望它是这样的:

Please enter a valid date for the Date of Birth.

我不要求用户输入日期,但是当他们输入无效值时,我想自定义错误。

4

4 回答 4

5

您可以对错误使用数据注释,或者,在这种情况下,您可以这样做:

@Html.ValidationMessageFor(m => m.DateOfBirth , "Please enter a valid date for the Date of Birth.") 
于 2011-09-28T16:10:21.340 回答
4

试试这个,

[DataType(DataType.Date, ErrorMessage = "Please enter a valid date.")]
public System.DateTime DateOfBirth { get; set; }

希望对你有帮助.. :)

于 2011-12-15T08:25:45.100 回答
1
public class myClass()
{

    [Display(Name="Date of Birth"), DataType(DataType.Date, ErrorMessage = "Please enter a valid date for the Date of Birth.")]
    public string dateOfBirth { get; set; }
}
于 2011-09-28T22:22:22.263 回答
0

对我来说,数据类型中的错误消息不起作用 使用常规删除它

[Display(Name="Date of Birth")]
[RegularExpression(@"^(3[01]|[12][0-9]|0[1-9])[-/](1[0-2]|0[1-9])[-/][0-9]{4}$", ErrorMessageResourceName = "DateNotValid", ErrorMessageResourceType = typeof(Resources))]
    public string dateOfBirth { get; set; }

DateNotValid : 在资源文件中使用。如果您想要上面的格式,您可以更改为错误消息:dd-MM-YYYYY

于 2014-06-27T03:47:04.173 回答