Firstly i used this solution to my problem: jQuery date validation MVC 4 .Net 4.5.1 UK date "must be a date" Error
- When I post a valid model, it all works just fine.
- When I post an invalid model without date it validates fine too.
- But when I post an invalid model with date it ends up by exception: Object reference not set to an instance of an object.
Here is date field in model:
[DataType(DataType.DateTime)]
[DisplayFormat(DataFormatString = "{0:dd.MM.yyyy HH:mm}")]
[Display(Name = "Date")]
public DateTime Date{ get; set; }
Here is code in create.cshtml
<div class="form-group">
@Html.LabelFor(model => model.Date, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(model => model.Date, "{0:dd.MM.yyyy HH:mm}", new { @Value = ViewBag.Date, @class = "form-control", @id = "datetimepicker" })
@Html.ValidationMessageFor(model => model.Date, "", new { @class = "text-danger" })
</div>
</div>
Javasript in layout.cshtml:
<script type="text/javascript">
jQuery('#datetimepicker').datetimepicker({
format: 'd.m.Y H:i',
lang: 'cs',
dayOfWeekStart: 1
});
And here is reworked jQuery date validation:
date: function (value, element) {
$.culture = Globalize.culture("cs-CZ");
var date = Globalize.parseDate(value, "dd.MM.yyyy HH:mm","cs-CZ");
return this.optional(element) ||
!/Invalid|NaN/.test(new Date(date).toString());
},
EDIT: so I finally maked it work by changing date function to a regular expression like this:
return value.match(/^(0?[1-9]|[12][0-9]|3[0-1])[/., -](0?[1-9]|1[0-2])[/., -](19|20)?\d{2} ([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/);