0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

flatpickrで期間が指定範囲より大きいときにアラートを出したい

Last updated at Posted at 2019-12-26

カレンダー表示する際に便利なflatpickrで
アラートなどを出してあげたいときに以下の書き方をしました。
※jQueryを使っています

/**
 * カレンダーテスト
 * @return なし
 */
// flatpickr実行 以下はクラス名
$('.inputDate').flatpickr({
  mode: 'range',
  locale: 'ja',
  maxDate: 'today',
  dateFormat: 'Y/m/d',
  defaultDate: ['2019/12/01', '2019/12/10'],
  allowInput: true,
  onClose: function(selectedDates, dateStr) {
    // 値が変更された時の処理
    if (!periodJudgment(selectedDates)) {
      alert('指定範囲が長すぎます!!');
    }
  },
});

function periodJudgment(selectedDates) {
  // 1年を日数で設定
  const oneYearDayCount = 365;
  // 選択期間が1年以上の日数の場合はfalseを返す
  let diffDate        = selectedDates[1] - selectedDates[0];
  const diffDateCount = Math.floor(diffDate / (1000 * 60 * 60 * 24));

  if (diffDateCount > oneYearDayCount) {
    return false;
  }
  return true;
}

HTMLは以下

<!-- flatpickrを使うために必要 --!>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
<script src="https://cdn.jsdelivr.net/npm/flatpickr/dist/l10n/ja.js"></script>

<!-- 日にち期間選択用inputフォーム --!>
<input class="inputDate" type="text" value="" />
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?