FormValidation v0.8.1 is released, supports Bootstrap 4 alpha 3

date validator

Validate a date

Validators

Options

* — Required option

Option HTML attribute Type Description
format* data-fv-date-format String The date format. It is MM/DD/YYYY, by default
max data-fv-date-max String|Date The value must be earlier than this option. It's a dynamic option
message data-fv-date-message String The error message
min data-fv-date-min String|Date The value must be later than this option. It's a dynamic option
separator data-fv-date-separator String

Used to separate the day, month, and year. If it's not defined, the validator will look for the following separators automatically:

  • /
  • -
  • . (which is used in most European countries)
When setting options via HTML attributes, remember to enable the validator by setting data-fv-date="true".
You don't need to do that when using HTML 5 type="date" attribute (the format then will be forced to be YYYY-MM-DD).

The min and max options can be either a date string in the format of YYYY-MM-DD or a Date object. If the form need to validate start and end date, you should take a look at the Validating fields that depend on each other or Compraing dates example.

The format can combine date, time, and AM/PM indicator sections:

Section Token Separator
Date DD, MM, YYYY Defined by the separator option.
Most popular ejemplos are a slash (/), hyphen (-), or dot (.)
Time h, m, s a colon (:)
AM/PM A n/a
The Validating multiple inputs as one example give you an idea of validating a date field which is combined by three separated fields presenting day, month and year.

The following table describes the token meanings, defined by momentjs, one of most popular Javascript datetime library:

Token Description Required
MM Month number Yes
DD Day of month Yes
YYYY 4 digit year Yes
h 12 hour time No
m Minutes No
s Seconds No
A AM/PM No

The date validator requires day, month and year. If you are looking for hour and time validator, HH:mm, for example, you should use the regexp validator. See the time example.

Use the callback validator in case you want to validate the date which one of year, month or day part is missing such as credit card expiration date

Below are some example of possible formats:

  • YYYY/DD/MM
  • YYYY/DD/MM h
  • YYYY/DD/MM h A
  • YYYY/DD/MM h:m
  • YYYY/DD/MM h:m A
  • YYYY/DD/MM h:m:s
  • YYYY/DD/MM h:m:s A
  • YYYY-MM-DD
  • YYYY-MM-DD h:m A
  • DD/MM/YYYY
  • DD/MM/YYYY h:m A
  • MM-DD-YYYY
  • MM-DD-YYYY h:m A
  • DD-MM-YYYY
  • DD-MM-YYYY h:m A

It's possible to support other date format by using callback validator as shown in the Custom format example.

The date validator also checks the number of days in February of leap year. For example, 2000/02/29 is a valid date, while 2001/02/29 is invalid one.
The message and other options can be updated on the fly via the updateMessage() and updateOption() methods

ejemplos

Basic example

The following form might be used in a profile setting page:

<form id="profileForm" class="form-horizontal">
    <div class="form-group">
        <label class="col-xs-3 control-label">Birthday</label>
        <div class="col-xs-4">
            <input type="text" class="form-control" name="birthday" placeholder="YYYY/MM/DD" />
        </div>
    </div>
</form>

<script>
$(document).ready(function() {
    $('#profileForm').formValidation({
        framework: 'bootstrap',
        icon: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            birthday: {
                validators: {
                    date: {
                        format: 'YYYY/MM/DD',
                        message: 'The value is not a valid date'
                    }
                }
            }
        }
    });
});
</script>
<form id="profileForm" class="form-horizontal"
    data-fv-framework="bootstrap"
    data-fv-icon-valid="glyphicon glyphicon-ok"
    data-fv-icon-invalid="glyphicon glyphicon-remove"
    data-fv-icon-validating="glyphicon glyphicon-refresh">

    <div class="form-group">
        <label class="col-xs-3 control-label">Birthday</label>
        <div class="col-xs-4">
            <input type="text" class="form-control" name="birthday" placeholder="YYYY/MM/DD"
                data-fv-date="true"
                data-fv-date-format="YYYY/MM/DD"
                data-fv-date-message="The value is not a valid date" />
        </div>
    </div>
</form>

<script>
$(document).ready(function() {
    $('#profileForm').formValidation();
});
</script>

Datetime picker example

The form below is an example of using the date validator with Bootstrap Datetime Picker:

<link href="/vendor/bootstrap-datetimepicker/css/bootstrap-datetimepicker.min.css" rel="stylesheet" />
<script src="//oss.maxcdn.com/momentjs/2.8.2/moment.min.js"></script>
<script src="/vendor/bootstrap-datetimepicker/js/bootstrap-datetimepicker.min.js"></script>

<style type="text/css">
/**
 * Override feedback icon position
 * See http://formvalidation.io/ejemplos/adjusting-feedback-icon-position/
 */
#meetingForm .dateContainer .form-control-feedback {
    top: 0;
    right: -15px;
}
</style>

<form id="meetingForm" class="form-horizontal">
    <div class="form-group">
        <label class="col-xs-3 control-label">Meeting time</label>
        <div class="col-xs-6 dateContainer">
            <div class="input-group date" id="datetimePicker">
                <input type="text" class="form-control" name="meeting" placeholder="MM/DD/YYYY h:m A" />
                <span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span></span>
            </div>
        </div>
    </div>
</form>

<script>
$(document).ready(function() {
    $('#datetimePicker').datetimepicker();

    $('#meetingForm').formValidation({
        framework: 'bootstrap',
        icon: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            meeting: {
                validators: {
                    date: {
                        format: 'MM/DD/YYYY h:m A',
                        message: 'The value is not a valid date'
                    }
                }
            }
        }
    });

    $('#datetimePicker').on('dp.change dp.show', function(e) {
        $('#meetingForm').formValidation('revalidateField', 'meeting');
    });
});
</script>

Disabling date example

It's possible to disable a particular date by triggering the success.validator.fv event and using the updateStatus() method. The example below shows how to treat all Sundays as not valid date.

You can try to choose a Sunday from the picker to see how it works in action.

<!-- Include Bootstrap Datepicker -->
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.3.0/css/datepicker.min.css" />
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.3.0/css/datepicker3.min.css" />

<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.3.0/js/bootstrap-datepicker.min.js"></script>

<style type="text/css">
/**
 * Override feedback icon position
 * See http://formvalidation.io/ejemplos/adjusting-feedback-icon-position/
 */
#eventForm .form-control-feedback {
    top: 0;
    right: -15px;
}
</style>

<form id="eventForm" method="post" class="form-horizontal">
    <div class="form-group">
        <label class="col-xs-3 control-label">Event</label>
        <div class="col-xs-5">
            <input type="text" class="form-control" name="name" />
        </div>
    </div>

    <div class="form-group">
        <label class="col-xs-3 control-label">Date</label>
        <div class="col-xs-5 date">
            <div class="input-group input-append date" id="datePicker">
                <input type="text" class="form-control" name="eventDate" />
                <span class="input-group-addon add-on"><span class="glyphicon glyphicon-calendar"></span></span>
            </div>
        </div>
    </div>

    <div class="form-group">
        <div class="col-xs-5 col-xs-offset-3">
            <button type="submit" class="btn btn-default">Validate</button>
        </div>
    </div>
</form>

<script>
$(document).ready(function() {
    $('#datePicker')
        .datepicker({
            format: 'mm/dd/yyyy'
        })
        .on('changeDate', function(e) {
            // Revalidate the date field
            $('#eventForm').formValidation('revalidateField', 'eventDate');
        });

    $('#eventForm')
        .formValidation({
            framework: 'bootstrap',
            icon: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            fields: {
                name: {
                    validators: {
                        notEmpty: {
                            message: 'The name is required'
                        }
                    }
                },
                eventDate: {
                    validators: {
                        notEmpty: {
                            message: 'The date is required'
                        },
                        date: {
                            format: 'MM/DD/YYYY',
                            message: 'The date is not a valid'
                        }
                    }
                }
            }
        })
        .on('success.validator.fv', function(e, data) {
            if (data.field === 'eventDate' && data.validator === 'date' && data.result.date) {
                // The eventDate field passes the date validator
                // We can get the current date as a Javascript Date object
                var currentDate = data.result.date,
                    day         = currentDate.getDay();

                // If the selected date is Sunday
                if (day === 0) {
                    // Treat the field as invalid
                    data.fv
                        .updateStatus(data.field, data.fv.STATUS_INVALID, data.validator)
                        .updateMessage(data.field, data.validator, 'Please choose a day except Sunday');
                } else {
                    // Reset the message
                    data.fv.updateMessage(data.field, data.validator, 'The date is not valid');
                }
            }
        });
});
</script>

If you want to show another message when user choose a Sunday, you can use the updateMessage() method:

$('#eventForm')
    .formValidation({
        ...
    })
    .on('success.validator.fv', function(e, data) {
        if (data.field === 'eventDate' && data.validator === 'date' && data.result.date) {
            var currentDate = data.result.date,
                day         = currentDate.getDay();

            // If the selected date is Sunday
            if (day === 0) {
                // Treat the field as invalid
                data.fv
                    .updateStatus(data.field, data.fv.STATUS_INVALID, data.validator)
                    // Update the message
                    .updateMessage(data.field, data.validator, 'Please choose a day except Sunday');
            } else {
                // Reset the message
                data.fv.updateMessage(data.field, data.validator, 'The date is not valid');
            }
        }
    });

Custom format example

This example illustrates the ability of validating date in custom format by using the callback validator and momentjs to parse/validate.

<script src="//oss.maxcdn.com/momentjs/2.8.2/moment.min.js"></script>

<form id="customFormatForm" class="form-horizontal">
    <div class="form-group">
        <label class="col-xs-5 control-label">What's US independence day?</label>
        <div class="col-xs-3">
            <input type="text" class="form-control" name="independenceDay" placeholder="MMM D" />
        </div>
    </div>
</form>

<script>
$(document).ready(function() {
    $('#customFormatForm').formValidation({
        framework: 'bootstrap',
        icon: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            independenceDay: {
                validators: {
                    callback: {
                        message: 'Wrong answer',
                        callback: function (value, validator) {
                            var m = new moment(value, 'MMMM D', true);
                            if (!m.isValid()) {
                                return false;
                            }
                            return (m.months() === 6 && m.date() === 4);
                        }
                    }
                }
            }
        }
    });
});
</script>

Date range example

The following form asks you to enter a date in the range of 2000/01/01 and 2020/12/30.

It can be implemented by using the min and max options.

<form id="rangeForm" class="form-horizontal">
    <div class="form-group">
        <label class="col-xs-3 control-label">Enter a date</label>
        <div class="col-xs-4">
            <input type="text" class="form-control" name="date" />
        </div>
    </div>
</form>

<script>
$(document).ready(function() {
    $('#rangeForm').formValidation({
        framework: 'bootstrap',
        icon: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            date: {
                validators: {
                    date: {
                        message: 'The date is not valid',
                        format: 'YYYY/MM/DD',
                        // min and max options can be strings or Date objects
                        min: '2000/01/01',
                        max: '2020/12/30'
                    }
                }
            }
        }
    });
});
</script>

You also can use the callback validator and isBefore(), isAfter() methods provided momentjs to check if the date is in the range.

<script src="//oss.maxcdn.com/momentjs/2.8.2/moment.min.js"></script>

<form id="rangeCallbackForm" class="form-horizontal">
    <div class="form-group">
        <label class="col-xs-3 control-label">Enter a date</label>
        <div class="col-xs-4">
            <input type="text" class="form-control" name="date" />
        </div>
    </div>
</form>

<script>
$(document).ready(function() {
    $('#rangeCallbackForm').formValidation({
        framework: 'bootstrap',
        icon: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            date: {
                validators: {
                    date: {
                        message: 'The date is not valid',
                        format: 'YYYY/MM/DD'
                    },
                    callback: {
                        message: 'The date is not in the range',
                        callback: function(value, validator) {
                            var m = new moment(value, 'YYYY/MM/DD', true);
                            if (!m.isValid()) {
                                return false;
                            }
                            return m.isAfter('2000/01/01') && m.isBefore('2020/12/30');
                        }
                    }
                }
            }
        }
    });
});
</script>