JavaScriptで日付が正しいかチェックする
以下の例ではyyyymmdd形式で入力された日付をyyyy/mm/ddに変換している
function checkDate(date) { let targetDate = (date).replace(/[^0-9]/g, ''); if (targetDate.length == 8) { let tempDate = targetDate.match(/([0-9]{4})([0-9]{2})([0-9]{2})/); let y = tempDate[1]; let m = tempDate[2]; let d = tempDate[3]; dt = new Date(y, m-1, d); if (dt.getFullYear() == y && dt.getMonth() == (m-1) && dt.getDate() == d) { let formatedDate = targetDate.replace(/([0-9]{4})([0-9]{2})([0-9]{2})/g, "$1/$2/$3"); console.log(formatedDate); } else { console.log('正しい日付を入力してください'); } } } // 動作結果 checkDate('20180201'); // 2018/02/01 checkDate('20180228'); // 2018/02/28 checkDate('20180229'); // 正しい日付を入力してください