使用日期对象的javascript日期验证

时间:2011-06-17 19:27:41

标签: javascript validation date

根据http://www.codingforums.com/archive/index.php/t-98569.html,可以使用javascript的日期对象完成日期验证。

我有一个类似的场景,我在单独的文本框中有单独的年,月,日期,通过正则表达式验证。现在我想利用JS的日期对象来检查像一个月中的日子和飞跃年度验证,不是由RegExp验证完成的。但上面链接中讨论的内容对我来说并不适用。 例如,

<script type="text/javascript">
   var dy= new Date(2001,2,30);
   alert(dy.getFullYear()+" "+dy.getMonth()+" "+dy.getDate());
</script>

按原样返回日期。难道dy.getMonth()不应该返回-1这样的东西来表明2月份不存在30天吗?如果使用Date对象无法做到这一点,请提供一些替代方法来验证日期。

更新: 我刚刚找到另一个链接(http://internotredici.com/article/checkdateinjavascript/),它说的是相同的。 PS:我正在研究JS1.2,它已经很老了。

3 个答案:

答案 0 :(得分:6)

您可以从日,月,年位开始生成日期,然后检查这些位是否正确。

function isvalid_mdy(s){
    var day, A= s.split(/\D+/).map(function(itm,i){return parseInt(itm,10)});
    A[0]-=1;
    try{
        day= new Date(A[2], A[0], A[1]);
        if(day.getMonth()== A[0] && day.getDate()== A[1]) return day;
        throw new Error('Bad Date ');
    }
    catch(er){
        return er.message;
    }
}
function isvalid_dmy(s){
    var day, A= s.split(/\D+/).map(function(itm,i){return parseInt(itm,10)});
    A[1]-=1;
    try{
        day= new Date(A[2], A[1], A[0]);
        if(day.getMonth()== A[1] && day.getDate()== A[0]) return day;
        throw new Error('Bad Date ');
    }
    catch(er){
        return er.message;
    }
}

答案 1 :(得分:2)

这可能对某人有所帮助。编写了一些可以执行日期验证的方法。可能有一些更好的方法,但我想出了这些。这有助于验证基于语言环境的格式的日期。 注意:输入字段中提供的日期格式和日期字符串齐头并进。

<script type="text/javascript">
        function validate() {

            var format = 'yyyy-MM-dd';

            if(isAfterCurrentDate(document.getElementById('start').value, format)) {
                alert('Date is after the current date.');
            } else {
                alert('Date is not after the current date.');
            }
            if(isBeforeCurrentDate(document.getElementById('start').value, format)) {
                alert('Date is before current date.');
            } else {
                alert('Date is not before current date.');
            }
            if(isCurrentDate(document.getElementById('start').value, format)) {
                alert('Date is current date.');
            } else {
                alert('Date is not a current date.');
            }
            if (isBefore(document.getElementById('start').value, document.getElementById('end').value, format)) {
                alert('Start/Effective Date cannot be greater than End/Expiration Date');
            } else {
                alert('Valid dates...');
            }
            if (isAfter(document.getElementById('start').value, document.getElementById('end').value, format)) {
                alert('End/Expiration Date cannot be less than Start/Effective Date');
            } else {
                alert('Valid dates...');
            }
            if (isEquals(document.getElementById('start').value, document.getElementById('end').value, format)) {
                alert('Dates are equals...');
            } else {
                alert('Dates are not equals...');
            }
            if (isDate(document.getElementById('start').value, format)) {
                alert('Is valid date...');
            } else {
                alert('Is invalid date...');
            }
        }

        /**
         * This method gets the year index from the supplied format
         */
        function getYearIndex(format) {

            var tokens = splitDateFormat(format);

            if (tokens[0] === 'YYYY'
                    || tokens[0] === 'yyyy') {
                return 0;
            } else if (tokens[1]=== 'YYYY'
                    || tokens[1] === 'yyyy') {
                return 1;
            } else if (tokens[2] === 'YYYY'
                    || tokens[2] === 'yyyy') {
                return 2;
            }
            // Returning the default value as -1
            return -1;
        }

        /**
         * This method returns the year string located at the supplied index
         */
        function getYear(date, index) {

            var tokens = splitDateFormat(date);
            return tokens[index];
        }

        /**
         * This method gets the month index from the supplied format
         */
        function getMonthIndex(format) {

            var tokens = splitDateFormat(format);

            if (tokens[0] === 'MM'
                    || tokens[0] === 'mm') {
                return 0;
            } else if (tokens[1] === 'MM'
                    || tokens[1] === 'mm') {
                return 1;
            } else if (tokens[2] === 'MM'
                    || tokens[2] === 'mm') {
                return 2;
            }
            // Returning the default value as -1
            return -1;
        }

        /**
         * This method returns the month string located at the supplied index
         */
        function getMonth(date, index) {

            var tokens = splitDateFormat(date);
            return tokens[index];
        }

        /**
         * This method gets the date index from the supplied format
         */
        function getDateIndex(format) {

            var tokens = splitDateFormat(format);

            if (tokens[0] === 'DD'
                    || tokens[0] === 'dd') {
                return 0;
            } else if (tokens[1] === 'DD'
                    || tokens[1] === 'dd') {
                return 1;
            } else if (tokens[2] === 'DD'
                    || tokens[2] === 'dd') {
                return 2;
            }
            // Returning the default value as -1
            return -1;
        }

        /**
         * This method returns the date string located at the supplied index
         */
        function getDate(date, index) {

            var tokens = splitDateFormat(date);
            return tokens[index];
        }

        /**
         * This method returns true if date1 is before date2 else return false
         */
        function isBefore(date1, date2, format) {
            // Validating if date1 date is greater than the date2 date
            if (new Date(getYear(date1, getYearIndex(format)), 
                    getMonth(date1, getMonthIndex(format)) - 1, 
                    getDate(date1, getDateIndex(format))).getTime()
                > new Date(getYear(date2, getYearIndex(format)), 
                    getMonth(date2, getMonthIndex(format)) - 1, 
                    getDate(date2, getDateIndex(format))).getTime()) {
                return true;
            } 
            return false;                
        }

        /**
         * This method returns true if date1 is after date2 else return false
         */
        function isAfter(date1, date2, format) {
            // Validating if date2 date is less than the date1 date
            if (new Date(getYear(date2, getYearIndex(format)), 
                    getMonth(date2, getMonthIndex(format)) - 1, 
                    getDate(date2, getDateIndex(format))).getTime()
                < new Date(getYear(date1, getYearIndex(format)), 
                    getMonth(date1, getMonthIndex(format)) - 1, 
                    getDate(date1, getDateIndex(format))).getTime()
                ) {
                return true;
            } 
            return false;                
        }

        /**
         * This method returns true if date1 is equals to date2 else return false
         */
        function isEquals(date1, date2, format) {
            // Validating if date1 date is equals to the date2 date
            if (new Date(getYear(date1, getYearIndex(format)), 
                    getMonth(date1, getMonthIndex(format)) - 1, 
                    getDate(date1, getDateIndex(format))).getTime()
                === new Date(getYear(date2, getYearIndex(format)), 
                    getMonth(date2, getMonthIndex(format)) - 1, 
                    getDate(date2, getDateIndex(format))).getTime()) {
                return true;
            } 
            return false;
        }

        /**
         * This method validates and returns true if the supplied date is 
         * equals to the current date.
         */
        function isCurrentDate(date, format) {
            // Validating if the supplied date is the current date
            if (new Date(getYear(date, getYearIndex(format)), 
                    getMonth(date, getMonthIndex(format)) - 1, 
                    getDate(date, getDateIndex(format))).getTime()
                === new Date(new Date().getFullYear(), 
                        new Date().getMonth(), 
                        new Date().getDate()).getTime()) {
                return true;
            } 
            return false;                
        }

        /**
         * This method validates and returns true if the supplied date value 
         * is before the current date.
         */
        function isBeforeCurrentDate(date, format) {
            // Validating if the supplied date is before the current date
            if (new Date(getYear(date, getYearIndex(format)), 
                    getMonth(date, getMonthIndex(format)) - 1, 
                    getDate(date, getDateIndex(format))).getTime()
                < new Date(new Date().getFullYear(), 
                        new Date().getMonth(), 
                        new Date().getDate()).getTime()) {
                return true;
            } 
            return false;                
        }

        /**
         * This method validates and returns true if the supplied date value 
         * is after the current date.
         */
        function isAfterCurrentDate(date, format) {
            // Validating if the supplied date is before the current date
            if (new Date(getYear(date, getYearIndex(format)), 
                    getMonth(date, getMonthIndex(format)) - 1, 
                    getDate(date, getDateIndex(format))).getTime()
                > new Date(new Date().getFullYear(),
                        new Date().getMonth(), 
                        new Date().getDate()).getTime()) {
                return true;
            } 
            return false;                
        }

        /**
         * This method splits the supplied date OR format based 
         * on non alpha numeric characters in the supplied string.
         */
        function splitDateFormat(dateFormat) {
            // Spliting the supplied string based on non characters
            return dateFormat.split(/\W/);
        }

        /*
         * This method validates if the supplied value is a valid date.
         */
        function isDate(date, format) {                
            // Validating if the supplied date string is valid and not a NaN (Not a Number)
            if (!isNaN(new Date(getYear(date, getYearIndex(format)), 
                    getMonth(date, getMonthIndex(format)) - 1, 
                    getDate(date, getDateIndex(format))))) {                    
                return true;
            } 
            return false;                                      
        }
    </script>

HTML日期关联输入字段

<input type="text" name="start" id="start" size="10" value="" />
<br/>
<input type="text" name="end" id="end" size="10" value="" />
<br/>
<input type="button" value="Submit" onclick="javascript:validate();" />

答案 2 :(得分:1)

在JS中,monht从0开始,因此0 = Jan,1 = Feb,2 = Mar

30,1(30 FEB)将于3月2日

你必须自己测试一下..

这可以帮助您 - validate-date