programer.tips, another cool thing from @nghuuphuoc!

date validator

Validate a date

Validators

Improve it on Github

Options

Option HTML attribute Type Description
format* data-bv-date-format String The date format. It is MM/DD/YYYY, by default
message data-bv-date-message String The error message
separator data-bv-date-separator String Used to separate the day, month, and year. It is /, by default
When setting options via HTML attributes, remember to enable the validator by setting data-bv-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 format can combine date, time, and AM/PM indicator sections:

Section Token Separator
Date DD, MM, YYYY Defined by the separator option.
Most popular examples are a slash (/), hyphen (-), or dot (.)
Time h, m, s a colon (:)
AM/PM A n/a
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.

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

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.

Examples

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-sm-3 control-label">Birthday</label>
        <div class="col-sm-3">
            <input type="text" class="form-control" name="birthday" placeholder="YYYY/MM/DD" />
        </div>
    </div>
</form>
$(document).ready(function() {
    $('#profileForm').bootstrapValidator({
        feedbackIcons: {
            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'
                    }
                }
            }
        }
    });
});
<form id="profileForm" class="form-horizontal"
    data-bv-feedbackicons-valid="glyphicon glyphicon-ok"
    data-bv-feedbackicons-invalid="glyphicon glyphicon-remove"
    data-bv-feedbackicons-validating="glyphicon glyphicon-refresh">

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

<script>
$(document).ready(function() {
    $('#profileForm').bootstrapValidator();
});
</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 */
#meetingForm .dateContainer .form-control-feedback {
    top: 0;
    right: -15px;
}
</style>

<form id="meetingForm" class="form-horizontal">
    <div class="form-group">
        <label class="col-sm-3 control-label">Meeting time</label>
        <div class="col-sm-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>
$(document).ready(function() {
    $('#datetimePicker').datetimepicker();

    $('#meetingForm').bootstrapValidator({
        feedbackIcons: {
            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').bootstrapValidator('revalidateField', 'meeting');
    });
});

Custom format example

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

<!-- Include the momentjs library to use later -->
<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-sm-5 control-label">What's US independence day?</label>
        <div class="col-sm-3">
            <input type="text" class="form-control" name="independenceDay" placeholder="MMM D" />
        </div>
    </div>
</form>
$(document).ready(function() {
    $('#customFormatForm').bootstrapValidator({
        feedbackIcons: {
            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);
                        }
                    }
                }
            }
        }
    });
});

Date range example

One more example illustrates how to use the callback validator and momentjs to check whether or not a date is in given range.

momentjs provides isBefore() and isAfter() methods which are exactly what we need.

<!-- Include the momentjs library to use later -->
<script src="//oss.maxcdn.com/momentjs/2.8.2/moment.min.js"></script>

<form id="rangeForm" class="form-horizontal">
    <div class="form-group">
        <label class="col-sm-6 control-label">Enter a date between 2000/01/01 and 2020/12/30</label>
        <div class="col-sm-3">
            <input type="text" class="form-control" name="date" />
        </div>
    </div>
</form>
$(document).ready(function() {
    $('#rangeForm').bootstrapValidator({
        feedbackIcons: {
            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');
                        }
                    }
                }
            }
        }
    });
});