Skip to content

Instantly share code, notes, and snippets.

@shinchit
Created June 20, 2014 12:58
Show Gist options
  • Save shinchit/3377347490b6c54475c0 to your computer and use it in GitHub Desktop.
Save shinchit/3377347490b6c54475c0 to your computer and use it in GitHub Desktop.
HTMLフォームに入力された日付(年月日)が現在日付(年月日)より過去に指定されているかどうか調べるJavaScript(jQuery使用)
$(function() {
// 1.現在日付(時分秒はゼロにセットする)を得る
var now = new Date();
now = new Date(now.getFullYear(), now.getMonth(), now.getDate());
// 2.フォームで指定された日付を得る
var year = $("#year");
var month = $("#month");
var day = $("#day");
// 3.年月日のセレクトボックスが変更されたタイミングで指定した日付と現在日付との比較を実行する
year.change(function() {
isSameOrFutureDate(now, year, month, day);
});
month.change(function() {
isSameOrFutureDate(now, year, month, day);
});
day.change(function() {
isSameOrFutureDate(now, year, month, day);
});
});
// 現在日付とフォームで指定された日付を比較
function isSameOrFutureDate(now, year, month, day) {
var specifiedDate = new Date(year.val(), month.val()-1, day.val());
if (now.getTime() >= specifiedDate.getTime()) {
alert("過去の日付が指定されています");
return false;
} else {
alert("現在日、および未来日付が指定されています");
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment