Integrating with Bootstrap Datepicker

The following example illustrates an usage of FormValidation with the Bootstrap Datepicker plugin.
You should look at the basic principle when integrating FormValidation with 3rd party libraries

Basic example

We need to revalidate the date field after picking a date from the date picker:
const fv = FormValidation.formValidation(
document.getElementById('demoForm'),
{
fields: {
date: {
...
},
}
}
);
$('[name="date"]')
.datepicker({
format: 'mm/dd/yyyy'
})
.on('changeDate', function(e) {
// Revalidate the date field
fv.revalidateField('date');
});
Basic example

Embedding a date picker

It's possible for Bootstrap Datepicker to embed a picker right on the page without attaching it to particular input field. In order to validate the selected date, firstly we need create a hidden input to keep the selected date:
<div id="embeddingDatePicker"></div>
<input type="hidden" id="selectedDate" name="selectedDate" />
We then add validator rules for the selectedDate field:
const form = document.getElementById('demoForm');
const fv = formValidation(form, {
fields: {
selectedDate: {
validators: {
notEmpty: {
message: 'The date is required',
},
date: {
format: 'MM/DD/YYYY',
message: 'The date is not a valid',
},
},
},
},
});
Finally, after choosing a date, you need to set the selected date to the hidden field, and revalidate it:
$('#embeddingDatePicker')
.datepicker({
format: 'mm/dd/yyyy',
})
.on('changeDate', function (e) {
// Set the value for the date input
document.querySelector('[name="selectedDate"]').value =
$('#embeddingDatePicker').datepicker('getFormattedDate');
// Revalidate it
fv.revalidateField('selectedDate');
});
You can try it with the following live form:
Embedding a date picker

Setting date in a range

Since Bootstrap Datepicker provides startDate and endDate options, and the date validator supports min and max options, we can set a date range easily. The following example asks to enter a date between 01/01/2010 and 12/30/2020.
Setting date in a range

Closing the date picker automatically

If you want to close the date picker immediately right after choosing a date, you need to set the autoclose option to true:
$('[name="date"]')
.datepicker({
autoclose: true, // It is false, by default
format: 'mm/dd/yyyy'
})
.on('changeDate', function(e) {
...
});
Closing the date picker automatically

See also