I have a date and a datetime field in my model :
[Display(Name = "Tanggal")]
[Required(ErrorMessage = "Tanggal harus diisi.")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime Date { get; set; }
[Display(Name = "Waktu Penumpukan")]
[DataType(DataType.DateTime)]
[DisplayFormat(DataFormatString = "{0:DD/MM/YYYY HH:mm:ss}", ApplyFormatInEditMode = true)]
public DateTime StackingDate { get; set; }
Im using bootstrap datetimepicker for DateTime field and HTML5 date picker for my date field.
<div class="form-group">
<div class="col-md-12">
@Html.LabelFor(model => model.Date)
@Html.EditorFor(model => model.Date, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Date, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-12">
@Html.LabelFor(model => model.StackingDate)
<div id="datetimepicker1" class="input-group date">
@Html.TextBoxFor(model => model.StackingDate, new { @class = "form-control" })
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
@Html.ValidationMessageFor(model => model.StackingDate, "", new { @class = "text-danger" })
</div>
</div>
I am using moments and modify known bug for datetime format in javascript
$.validator.methods.date = function (value, element) {
return this.optional(element) || moment(value, "DD/MM/YYYY HH:mm:ss", true).isValid();
}
and my datetimepicker javascript initiazation look like this :
$('#datetimepicker1').datetimepicker({
format: 'DD/MM/YYYY HH:mm:ss'
});
I dont use bootstrap datetime picker for Date field because I am using HTML5 default date. It is working fine for datetime field, but I got error for date.
The field Tanggal must be a date.
If I remove the validator, it is working good for date but same error for datetime field.
I found that the validator can be filter by id
$.validator.methods.date = function (value, element) {
if (element.id === "Date") {
// For the "Tanggal" field, validate using HTML5 format
return this.optional(element) || moment(value, "YYYY-MM-DD", true).isValid();
} else {
// For the "StackingDate" field, validate using custom format
return this.optional(element) || moment(value, "DD/MM/YYYY HH:mm:ss", true).isValid();
}
};