Reputation: 6593
I am using Backbone.js with a Bootstrap Datepicker in my form.
The brief was to allow the client to use the 'dd.mm.yyyy' format, so I set the option on the datepicker.
self.$el.find('[data-role="invoicedate"]').datepicker({
format: "dd.mm.yyyy",
todayBtn: "linked",
todayHighlight: true,
language: Application_language
});
Then the client wanted to allow 'dd.mm.yy' also, and to have it autotranslated, so I did the following:
invoicedateToModel: function() {
var invoicedate = this.$el.find('[data-role="invoicedate"]').val();
var re2 = /^(\d{2})\.(\d{2})\.(\d{2})$/;
if (re2.test(invoicedate)) {
invoicedate = invoicedate.replace(re2,"$1.$2.20$3");
}
var re4 = /^(\d{2})\.(\d{2})\.(\d{4})$/;
if (re4.test(invoicedate)) {
this.saveInvoiceDate(invoicedate);
this.displayInvoiceDate();
this.$el.find('[data-role="invoicedate"]').parent().toggleClass('has-error', false);
} else {
this.$el.find('[data-role="invoicedate"]').parent().toggleClass('has-error', true);
}
},
and bound it to the change event on the input. This worked fine, I now realize, because dd.mm.yy fits in the dd.mm.yyyy format, ie it does not contradict it.
Now the client wants to also be able to add ddmmyyyy as an entry option, but the datepicker autocorrects the form by replacing the newly entered date with the last known good one, or todays date, because ddmmyyyy does not match with dd.mm.yyyy, before the callback above gets called.
Is there any way to tell bootstrap-datepicker about multiple allowed formats?
Upvotes: 3
Views: 3961
Reputation: 9876
You can pass functions to datepicker's format option. For really flexible parsing, I used moment.js.
$(".datepicker").datepicker({
format: {
toDisplay: function(date, format, language) {
return moment(date).format("MM/DD/YYYY");
},
toValue: function(date, format, language) {
return moment(date, ["DD.MM.YYYY", "DDMMYYYY"]).toDate();
}
}
});
From the bootstrap-datepicker docs:
toDisplay: function (date, format, language) to convert date object to string, that will be stored in input field
toValue: function (date, format, language) to convert string object to date, that will be used in date selection
You may have to play around with the moment()
options, but you should be able to get it to where you want it. Check out momentjs's docs as well.
Upvotes: 3