Search code examples
c#asp.net-mvcvalidationdatetimeunobtrusive-validation

How correctally validate DateTime in MVC Unobtrusive Validation?


Im triying to validade a datetime field with inobstrusive validation.

If the input is 01/01/2017 10:00 then I get

The field [fieldId] must be a date.

However the field must not be a date, but a datetime.

The parameter is set like this in my model:

    [Display(Name = "Start")]
    [DataType(DataType.DateTime)]
    public DateTime start { get; set; }

I was not able to correctally validate a field with datetime input.

How can I do this?


Solution

  • Keep in mind that specifying the DataType does not do validation. All it does is provide a hint to the browser as to what kind of input is expected. To validate, try adding a regular expression validator, like so:

    [RegularExpression(@"^((((31\/(0?[13578]|1[02]))|((29|30)\/(0?[1,3-9]|1[0-2])))\/(1[6-9]|[2-9]\d)?\d{2})|(29\/0?2\/(((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))|(0?[1-9]|1\d|2[0-8])\/((0?[1-9])|(1[0-2]))\/((1[6-9]|[2-9]\d)?\d{2})) (20|21|22|23|[0-1]?\d):[0-5]?\d$", ErrorMessage = "Date must be in the format of : dd/mm/yyyy hh:mm"]
    [Display(Name = "Start")]
    [DataType(DataType.DateTime)]
    public DateTime start { get; set; }