5
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 5 years have passed since last update.

input type="date"非対応ブラウザで、日付チェック

Last updated at Posted at 2018-06-26

input type="date"で不正な日付(2018-02-29とか)を入力した時に対応していないブラウザでもエラーチェックを行う方法メモ
(IEはともかく、Safari最新版が非対応なのは意外。)

結論

<input type="date" id="date">
// フォームの入力値を取得
var dVal = document.getElementById("date").value;
// Dateオブジェクトを作成する。
var date = new Date(dVal);
// Dateオブジェクトにキャスト出来てなければInvalid Dateというオブジェクトが格納されているので、そのチェック
if (date.toString() === "Invalid Date") {
    alert('NG...');
    return;
}
// フォームに入力された年と月を取得する
var ymdArray = dVal.split(dVal.toString().indexOf("/") !== -1 ? "/" : "-");
var y = parseInt(ymdArray[0]);
var m = parseInt(ymdArray[1]);

// 年月が変わっていれば不正と判定
if (y === date.getFullYear() && m === date.getMonth() + 1) {
    alert('OK!');
} else {
    alert('NG...');
}

解説

"2018/01/32"と入力された時、 new Date("2018/01/32")した結果は2018/02/01となる。
なので、入力された月とDateオブジェクトから取得した月が違えば、不正な日付だと判定できる。
ただし、Date.getMonth()は0~11の値を返すため、+1しないとダメ。

参考にしたページはこちら

但し、上記サイトのように月だけで判定してしまうと2018/02/366とかでもOKになってしまうので、年でも比較する必要がある。

5
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
5
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?