通过javascript

时间:2016-01-06 15:49:37

标签: javascript php

我想通过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>

即使我把明天的日期记录下来,它总是会返回(日期还剩下。)

问题是什么?

2 个答案:

答案 0 :(得分:3)

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

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)
    ^^^^^^^

答案 1 :(得分:0)

如果您使用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规范声明:如果String不符合   该功能的标准格式可以归结为任何   特定于实现的启发式或特定于实现的解析   算法。无法识别的字符串或包含非法元素的日期   ISO格式字符串中的值将导致Date.parse()返回   为NaN。

     

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

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

将被视为2015年11月25日在Firefox 30和Firefox中的当地日期   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。字符串&#34; 10 06 2014&#34;是一个不符合的例子   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
相关问题