在javascript中验证出生日期


validate birthdate in javascript

我想通过JavaScript函数验证出生日期。

这是JavaScript函数:

function dat() {
    var myDate1 = document.getElementById("d").value;
    var month  = myDate1.substring(0, 2) - 1;
    var date   = myDate1.substring(3, 5) - 0;
    var year   = myDate1.substring(6, 10) - 0;
    var myDate = new Date(year, month, date);
    var today  = new Date();
    if (myDate1 > today) {
        document.getElementById('dd').innerHTML = "";
        document.getElementById("d").style.borderColor = "green";
    }
    else if (myDate1 < today) {
        document.getElementById('dd').innerHTML = myDate1;
        document.getElementById("d").style.borderColor = "red";
    }
    if (document.getElementById("d").value == "") {
        document.getElementById('dd').innerHTML = "This Field  Is Required";
        document.getElementById("d").style.borderColor = "red";
    }
}

这是html输入

<div class="form-group">
<label for="d">Date Of Birth</label>
<div class="input-group">
    <input type="date" class="form-control" name="d" id="d" 
           onKeyUp="dat()" placeholder="mm/dd/yyyy"/>
    <p>
    <div style="color:red" id="dd"></div>
    </p>
    <span class="input-group-addon"></span>
</div>

即使我把明天的日期放进去,它也总是会回来(日期是左边的)。

问题出在哪里?

您将日期与输入值进行比较,而不是与日期对象进行比较。

var myDate1= document.getElementById("d").value;  <-- You are using this
var myDate= new Date(year,month,date);            <-- Not this
var today = new Date();
if (myDate1>today)
    ^^^^^^^

如果您使用mm/dd/yyyy格式的日期,您可以简单地使用Date.parse,而不是编写自己的日期解析器。

这样做:

var utime = Date.parse(yourDate)
if (utime == NaN)  {
    alert('Invalid date');
} else if (utime < new Date()) {
    alert('Valid birth date! It''s in the past');
} else {
   alert('Invalid birth date! It''s in the future');
}

警告

如MDN:中所述

回退到具体实施的日期格式

ECMAScript规范规定:如果字符串不符合函数可以回退到任何标准格式具体实施启发式或具体实施解析算法。包含非法元素的无法识别的字符串或日期ISO格式字符串中的值应导致Date.parse()返回NaN。

但是,日期字符串中的无效值无法识别为ISO格式ES5定义的可能会或可能不会导致NaN,这取决于浏览器和提供的值,例如:

// Non-ISO string with invalid date values
new Date('23/25/2014');

在Firefox 30和Safari 7中的无效日期。但是,如果字符串被识别为一个ISO格式的字符串,并且它包含无效值,它将返回所有符合ES5:的浏览器中的NaN

// ISO string with invalid values
new Date('2014-25-23').toISOString();
// returns "RangeError: invalid date" in all es5 compliant browsers

SpiderMonkey的具体实现启发式可以在jsdate.cpp。字符串"10 06 2014"是不符合ISO格式,因此返回到自定义例程。另请参阅解析工作原理的大致概述。

new Date('10 06 2014');

将被视为2014年10月6日而非6月10日的当地日期,2014.其他示例:

new Date('foo-bar 2014').toString();
// returns: "Invalid Date"
Date.parse('foo-bar 2014');
// returns: NaN