用于验证日期的JavaScript [英] JavaScript to validate date

查看:75
本文介绍了用于验证日期的JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是验证日期的功能。应该在今天 - 15 今天之间。有人可以重构这段代码。

Below is the function to validate date. The should be between Today - 15 and Today. Can some one refactor this code.

phpdatetoday是一个字符串,形式为 2010年12月3日

phpdatetoday is a string in the form 2010,Dec,3

function validate(page, phpdatetoday)
{
    var i = 0;
    var fields    = new Array();
    var fieldname = new Array();

    var day   = document.getElementById('date_of_inspection_day').value;
    var month = document.getElementById('date_of_inspection_month').value;
    var year  = document.getElementById('date_of_inspection_year').value;
    var datesubmitted = new Date(year,month-1,day);

    var daysInMonth = new Array(31,29,31,30,31,30,31,31,30,31,30,31);

    if(month.length<1 )
    {
        alert("Please enter a valid month");
        return false;
    }
    if(year.length != 4 )
    {
        alert("Please enter a valid year");
        return false;
    }

    if (day.length<1 || day > daysInMonth[month-1] || month == 2 && year%4 != 0 && day >28 )
    {
        alert("Please enter a valid day");
        return false;
    }

    var dateToday  = new Date(phpdatetoday);
    var day15      = dateToday.getDate()-15; // 15 days old
    var month15    = dateToday.getMonth();
    var year15     = dateToday.getFullYear();

    if(day15 < 0 && month15 ==1)
    {
        month15 = 12;
        year15  = year15-1;
    }
    else if(day15 < 0 && month15 !=1)
    {
        month15 = month15-1;
    }

    day15   = daysInMonth[month15-1] + day15;

    var date15DayOld  = new Date(year15,month15,day15);

    if(date15DayOld > datesubmitted )
    {
        alert("Your date is older than 15 days");
    }

    else if(datetoday < datesubmitted )
    {
        alert("invalid Date");
    }
}


推荐答案

function validate(phpdatetoday, withinDays) {
    var inputDateInMillis = Date.parse(phpdatetoday)

    if (isNaN(inputDate) || isNaN(withinDays)) {
        //handle error
        return;
    }

    var todayInMillis = (new Date()).setHours(0,0,0,0);
    return todayInMillis - inputDateInMillis < (withinDays * 86400000 /*1000ms*60s*60m*24h*/);
}

Date.setHours()会将小时/分钟/秒设置为零,返回自1970年1月1日UTC以来的毫秒数。

Date.setHours() will set the hours/minutes/seconds to zero and return milliseconds since 1 Jan 1970 UTC.

Date.parse()将返回已解析的日期,否则如果无法执行,则返回NaN。您可以使用isNan()来确定变量的值是否为数字。如果'inputDate'是NaN,那么您可以提醒用户输入日期无效。

Date.parse() will return the parsed date otherwise if it cannot do it then it will return NaN. You can use isNan() to determine whether a variable's value is a number or not. If 'inputDate' is NaN then you can alert the user that the input date was invalid.

这篇关于用于验证日期的JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆