使用mvc3中的DataAnnotations验证文本框以仅接受有效的日期时间值

Jit*_*mar 2 c# data-annotations asp.net-mvc-3

我想使用MVC3中的DataAnnotations验证文本框以接受日期时间值.但我不知道该怎么做.鉴于以下是我正在努力完成我的要求而且它无法正常工作.

    [DataType(DataType.DateTime, ErrorMessage = "Invalid Datetime")]
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy HH:mm}")]
    [Display(Name = "Start Datetime")]
    public DateTime? StartDateTime { get; set; }
Run Code Online (Sandbox Code Playgroud)

当我在填写损坏的数据后点击提交按钮时,第一个问题是该表单获取帖子,之后它显示"无效日期"的消息,如果我输入的日期没有时间仍然形式获得发布,但这次它没有显示消息也是错误的.

所以我只想知道如何使用MVC DataAnnotations验证我的文本框以"dd/MM/yyyy HH:mm"格式接受日期时间.

Zaf*_*far 9

1.您的客户端验证无效.提交表单后您看到错误消息 - 表示客户端验证无法正常工作.为了使客户端验证工作,ASP.NET MVC假定您在页面上拥有jquery.validate.jsjquery.validate.unobtrusive.js引用.您可以在Visual Studio上使用NuGet Package Manager下载它们.

2.日期字段未经过验证.您期望DisplayFormat为您验证日期格式.但事实上并非如此.这更多的是关于在视图上显示您的日期.

要验证日期格式,您需要使用自己的自定义Attribute.或者你可以简单地使用RegularExpression属性.最简单的示例如下所示:

[RegularExpression(@"\d{1,2}/\d{1,2}/\d{2,4}\s\d{1,2}:\d{1,2}", ErrorMessage = "")]
Run Code Online (Sandbox Code Playgroud)

或者,如果要创建自定义属性,则:

public class DateFormatValidation : ValidationAttribute{
    protected override bool IsValid(object value){
        DateTime date;
        var format = "0:dd/MM/yyyy HH:mm"
        bool parsed = DateTime.TryParseExact((string)value, format, System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None, out date)
        if(!parsed)
            return false;
        return true;
    } 
}
Run Code Online (Sandbox Code Playgroud)

然后使用它像:

[DataType(DataType.DateTime, ErrorMessage = "Invalid Datetime")]
[DateFormatValidation]
[Display(Name = "Start Datetime")]
public DateTime? StartDateTime { get; set; }
Run Code Online (Sandbox Code Playgroud)