简体   繁体   English

JavaScript - 确保日期有效

[英]JavaScript - making sure a date is valid

I have 3 drop down boxes to show a start date (day/month/year).我有 3 个下拉框来显示开始日期(日/月/年)。 I have 3 more to show an end date.我还有 3 个要显示结束日期。

I wish to validate that我想验证一下

  • The user picks a valid date (ie not the 30th February).用户选择一个有效日期(即不是 2 月 30 日)。 If they pick an invalid date, alert("Your date is invalid.")如果他们选择了一个无效的日期, alert("Your date is invalid.")
  • That the difference in days between the start and end dates is less than 7.开始日期和结束日期之间的天数差异小于 7。

I am really struggling with this and was hoping someone could help me as a relative beginner.我真的很挣扎,希望有人可以帮助我作为一个相对的初学者。

My code so far is as follows :到目前为止,我的代码如下:

<script type="text/javascript">
    var monthtext=["01","02","03","04","05","06","07","08","09","10","11","12"];

    function populatedropdown(dayfield, monthfield, yearfield){
    var today=new Date()
    var dayfield=document.getElementById(dayfield)
    var monthfield=document.getElementById(monthfield)
    var yearfield=document.getElementById(yearfield)
    for (var i=0; i<=31; i++)
       dayfield.options[i]=new Option(i, i)
    dayfield.options[today.getDate()]=new Option(today.getDate(), today.getDate(),     true, true) //select today's day
    for (var m=0; m<12; m++)
      monthfield.options[m]=new Option(monthtext[m], monthtext[m])
    monthfield.options[today.getMonth()]=new Option(monthtext[today.getMonth()], monthtext[today.getMonth()], true, true) //select today's month
    var thisyear=today.getFullYear()
    for (var y=0; y<4; y++){
      yearfield.options[y]=new Option(thisyear, thisyear)
      thisyear+=1
    }
    yearfield.options[0]=new Option(today.getFullYear(), today.getFullYear(), true, true) //select today's year
    }
</script>

HTML: HTML:

        <label>Start date :</label>
            <select name="startDateDay" id="startDaydropdown"></select> 
            <select name="startDateMonth" id="startMonthdropdown"></select> 
            <select name="startDateYear" id="startYeardropdown"></select>

        <label>End date :</label>
            <select name="endDateDay" id="endDaydropdown"></select> 
            <select name="endDateMonth" id="endMonthdropdown"></select> 
            <select name="endDateYear" id="endYeardropdown"></select>

Why not just have two text fields to let the user type in the date, then let new Date(textfield.value) do the heavy lifting of date validation?为什么不只有两个文本字段让用户输入日期,然后让new Date(textfield.value)完成日期验证的繁重工作?

Then you only need to worry about determining that the dates are within 7 days of each other.那么您只需要担心确定日期彼此相差在 7 天内。 You can do that part fairly easily with the Date object , perhaps with something as simple as:您可以使用Date 对象轻松完成该部分,也许使用以下简单的方法:

var dateDiff = date2.getTime()  - date1.getTime();
if(dateDiff <= 1000*60*60*24*7 && dateDiff > 0) {
    return 'valid';
} else {
    return 'invalid';
}

If running this as part of the submit button, your code would be something like:如果将此作为提交按钮的一部分运行,您的代码将类似于:

function validateDatesOnSubmit() {
    var date1 = new Date(document.getElementById('startDate').value);
    var date2 = new Date(document.getElementById('endDate').value);
    if(date1 == "Invalid Date" || date2 == "Invalid Date") {
        alert("You have entered an invalid date, please fix this.");
        return false;
    }
    var dateDiff = date2.getTime() - date1.getTime();
    if(dateDiff <= 1000*60*60*24*7 && dateDiff >= 0) {
        return true;
    } else {
        alert("You have entered a range beyond one week, please reduce the number of days selected.");
        return false;
    }
}
document.getElementById('myForm').onsubmit = validateDatesOnSubmit;

Assuming date is in the format dd-mm-yyyy or dd/mm/yyyy then:假设日期的格式为dd-mm-yyyydd/mm/yyyy则:

function toDate(t) {
  var t = t.split(/[-\/]/g);
  return new Date(t[2],t[1] - 1, t[0]);
}

function within7Days(t0, t1) {
  var d0 = toDate(t0);
  var d1 = toDate(t1);
  return d0.setDate(d0.getDate() + 7) > d1;
}

alert(within7Days('12-3/2012', '18/3/2012')); // true
alert(within7Days('12-3/2012', '19/3/2012')); // false

If the date can be before or after, you might want to use Math.abs()如果日期可以在之前或之后,您可能需要使用Math.abs()

Edit编辑

Incidentally, do not trust Date.parse .顺便说一句,不要相信Date.parse In ECMA-262 ed 3 it is essentially implementation dependent.在 ECMA-262 ed 3 中,它本质上是依赖于实现的。 In ES5 it is specified as first attempting to parse the string as ISO8601, but after that, it is implementation idependant.在 ES5 中,它被指定为首先尝试将字符串解析为 ISO8601,但在此之后,它取决于实现。 IE (<9 at least) will not correctly parse an ISO8601 date string. IE(至少 <9)不会正确解析 ISO8601 日期字符串。

In any case, manually parsing a date is trivial.在任何情况下,手动解析日期都是微不足道的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM