I am currently developping a MVC Asp.Net 4.6 WebApp with Bootstrap 3.1.1, Eonasdan datetime picker v4.7.14 and jquery validation plugin v1.14.0.
And I've got some problem validating the date.
My Model looks like that:
public class PersonModel{
...
[Required]
[Display(Name = "Date of Birth")]
public DateTime? DateOfBirth { get; set; }
...
}
My View looks like that:
<div class="form-group">
@Html.LabelFor(x => x.DateOfBirth):
<span class="text-danger"><b>*</b></span>
<div class="input-group datepicker">
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
@Html.TextBoxFor(x => x.DateOfBirth, new {@class = "form-control", @data_date_format = "DD/MM/YYYY", @placeholder = "DD/MM/YYYY"})
</div>
@Html.ValidationMessageFor(x => x.DateOfBirth, "", new { @class = "text-danger" })
</div>
The associated Js code to init th datetime picker:
(function () {
// Init bootstrap date/time pickers
$(".datepicker").datetimepicker({
useCurrent: false
});
})(jQuery);
Using jQuery.validator
, even if the the date looks good, I always get this error:
I know that jQuery.validator
works fine with the jquery.ui.datepicker but how can I make it work with the bootstrap.datetimepicker ?
You can overrides the date
method of the Jquery.validator
plugin :
(function () {
// overrides the jquery date validator method
jQuery.validator.methods.date = function (value, element) {
// All dates are valid....
return true;
};
})(jQuery);
Because the bootstrap datetime picker use moment.js, you can check if the date is valid like that:
(function () {
// overrides the jquery date validator method
jQuery.validator.methods.date = function (value, element) {
// We want to validate date and datetime
var formats = ["DD/MM/YYYY", "DD/MM/YYYY HH:mm"];
// Validate the date and return
return moment(value, formats, true).isValid();
};
})(jQuery, moment);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With