小池啓仁 ヒロヒト応援ブログ By はてな

小池啓仁(コイケヒロヒト)の動画など。

小池啓仁 ヒロヒト応援ブログ By はてな

日付チェックルーチン for JavaScript

以下は、閏年も対応できるJavaScriptでの日付チェックルーチンです。
標準オブジェクトDateの以下の特性を利用して、入力日付をチェックしています。
Dateの引数に2008/2/30を与えると2008/3/1を返す。

<html>
<body>
<form name="FM">
<p><input type="text" name="text1"></p>
<p><input type="button" onClick="checktest()" value="test"></p>
</form>
<script type='text/javascript'>
function checktest() {
   alert(isDate(document.FM.text1.value));
}
function isDate(text) {
    if (text.length == 0 || text== "") {
        return false;
    }
    var arrDate = text.split("/");
    if(arrDate.length == 3) {    
        var date = new Date(arrDate[0] , arrDate[1] - 1 ,arrDate[2]);
        if(date.getFullYear() == arrDate[0] && 
          (date.getMonth() == arrDate[1] - 1) && 
           date.getDate() == arrDate[2]) {
            return true;
        }
    }
    return false;
}
</script>
</body>
</html>