【问题标题】:javascript date validation using date object使用日期对象的 javascript 日期验证
【发布时间】:2011-06-17 19:27:40
【问题描述】:

根据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 的东西来表明二月份不存在 30 天吗?如果使用 Date 对象无法做到这一点,请提出一些替代方法来验证日期。

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

【问题讨论】:

    标签: javascript validation date


    【解决方案1】:

    您可以根据日、月、年位来制作日期,然后检查这些位是否正确。

    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;
        }
    }
    

    【讨论】:

    • 感谢肯尼贝克。我会调查一下。
    【解决方案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();" />
    

    【讨论】:

      【解决方案3】:

      在 JS 中,monht 从 0 开始,所以 0=Jan,1=Feb,2=Mar

      30,1(2 月 30 日)将是 3 月 2 日

      你必须自己测试这个..

      这可以帮助你 - validate-date

      【讨论】:

      • 谢谢!这就解释了。但是链接的站点似乎在正则表达式验证本身方面存在缺陷!。它接受像 42/42/4242 这样的值作为日期。
      • 我认为这个可行.. mkyong.com/regular-expressions/…
      猜你喜欢
      • 2014-09-08
      • 1970-01-01
      • 2021-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多