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) {
fv.revalidateField('date');
});
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) {
document.querySelector('[name="selectedDate"]').value = $('#embeddingDatePicker').datepicker('getFormattedDate');
fv.revalidateField('selectedDate');
});
You can try it with the following live form:
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.
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,
format: 'mm/dd/yyyy'
})
.on('changeDate', function(e) {
...
});
Closing the date picker automatically
See also