Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Client-side validation of input type date does not work

I have a form containing a date and datetime field:

@Html.TextBoxFor(model => model.A, new { @type = "datetime" })
@Html.TextBoxFor(model => model.B, new { @type = "date" })

Model:

public class TestModel
{
  [DataType(DataType.Date)]
  public DateTime A {get;set;}

  [DataType(DataType.Date)]
  public DateTime B {get;set;}
}

By using these input types an iPad shows nice date(time) pickers. The fields are validated using client-side validation. For the datetime field (A) it works, but the date field (B) will raise an error: "please enter a valid date." How do I solve this?

Examples:

  • This iPad (Safari) value for datetime is valid (according to MVC client-side validation): 15 dec. 2011 9:20
  • This iPad (Safari) value for date is invalid: 15 dec. 2011

It's hard to debug code on an iPad, so I have no clue how Safari changes the date format when setting the input's value attribute.

Edit: I discovered the datetime format is universal datetime format (yyyy-MM-DDTHH:mmZ), while the date format is yyyy-MM-dd. Probably the client-side validator does understands universal datetime and not yyyy-MM-dd due to localization.

like image 713
Marthijn Avatar asked Dec 15 '11 08:12

Marthijn


1 Answers

I had the exact same problem and was maddened beyond belief when viewing a mobile site I'm developing on my iPhone. The discussion in the issue below solved it for me.

https://github.com/jzaefferer/jquery-validation/issues/20.

Also, to go the distance with this in a seamless way, I created the following razor editor template for Date data types:

@model DateTime?
@Html.TextBox("myDate", ViewData.Model.ToIso8601FullDate(), new { type = "date", @class = "text-box single-line" })

and a handy extension method to feed the html 5 date input type a format it enjoys working with according to the spec for input type=date:

public static string ToIso8601FullDate(this DateTime? d)
{
    if (!d.HasValue) return null;

    return d.Value.ToString("yyyy-MM-dd");
}
like image 138
spot Avatar answered Nov 14 '22 23:11

spot