Playing with Bootstrap Datepicker

The following example illustrates an usage of FormValidation with the Bootstrap Datepicker plugin.

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');
    });

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:


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:

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, // It is false, by default
        format: 'mm/dd/yyyy'
    })
    .on('changeDate', function(e) {
        ...
    });