Skip to content

Instantly share code, notes, and snippets.

@raiderrobert
Created May 18, 2016 18:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raiderrobert/b83f096c0f3c37cc8c0014d6375d32c7 to your computer and use it in GitHub Desktop.
Save raiderrobert/b83f096c0f3c37cc8c0014d6375d32c7 to your computer and use it in GitHub Desktop.
Date enforcer dependent on jquery and moment
var dateEnforcer = function (startDate, endDate) {
$(startDate).on('focus', function () {
this.previousDate = moment(this.value).format('MM-DD-YYYY');
}).change(function(){
var newDate = moment(this.value).format('MM-DD-YYYY');
var endDateMoment = moment($(endDate).val()).format('MM-DD-YYYY');
if (this.previousDate != 'Invalid date'){
if (moment(newDate).isAfter(endDateMoment)){
$(endDate).val(newDate);
}
} else {
$(endDate).val(newDate);
}
});
$(endDate).on('focus', function () {
this.previousDate = moment(this.value).format('MM-DD-YYYY');
}).change(function(){
var newDate = moment(this.value).format('MM-DD-YYYY');
var startDateMoment = moment($(startDate).val()).format('MM-DD-YYYY');
if (this.previousDate != 'Invalid date'){
if (moment(newDate).isBefore(startDateMoment)){
$(startDate).val(newDate);
}
} else {
$(startDate).val(newDate);
}
});
};
dateEnforcer('#id_from_date', '#id_to_date');
@raiderrobert
Copy link
Author

This compares dates so that if you're using a calendar widget and are having a date that has a range that it should apply to, this will ensure you can't flip the range accidentally.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment