LoginSignup
0
0

More than 1 year has passed since last update.

JavaScriptで日付のバリデーションチェックをする方法

Last updated at Posted at 2021-05-11
var yyyy = document.form.year.value;
var mm = document.form1.month.value;
var dd = document.form2.date.value;
var date = new Date(yyyy, mm-1, dd);


    if(date.getFullYear() != yyyy || date.getMonth() != mm-1 || date.getDate() != dd) {
        alert("期限の入力が不正です。");
    } else {
        window.location.href = 'sample.html';
    }

解説

想定しているのは、○年○月○日というように、○の部分を入力フォームにして、整合性チェックをするというもの。
正しい日付が入力されたら画面遷移するプログラムとなっている。

まずは、フォームに入力された値を取得してそれぞれの変数に代入。
getMonth()は、デフォルトでは0~11の範囲を取るので、mm-1とすることで整合性を取る。
それぞれの変数がgetFullYear()、getMonth()、getDate()と比較して正しい値かチェック。どれか1つでも不適合ならアラートを出す。

ハマったエラー

存在しない日付を入力しても、バリデーションを通過してしまうエラーが発生。ネットの通りに書いてもなぜか通貨…。コードを見直すと、getMonth()の()の記述漏れでした。。
気づくのに1時間かかってしまった…

0
0
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
0