首页 > 解决方案 > jQuery:检查日期格式是否有效

问题描述

如何使用 jQuery 检查日期格式是否有效?

01/23/2017 --> true
23/01/2017 --> true
23-01-2017 --> true
01/23 --> true
23/01 --> true
23-01 --> true
23/23 --> false
23-23 --> false

标签: jquerydate-format

解决方案


请看答案。在自定义中验证输入日期的最简单方法

$(document).ready(function () {
    $('#btn_move').click(function () {
        var dateformat = /^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-]|1[012])\/\-]\d{4}$/;
        var Val_date = $('#txt_date').val();
        if (Val_date.match(dateformat)) 
        {
            var seperator1 = Val_date.split('/');
            var seperator2 = Val_date.split('-');

            if (seperator1.length > 1) 
            {
                var splitdate = Val_date.split('/');
            } 
            else if (seperator2.length > 1) 
            {
                var splitdate = Val_date.split('-');
            }
            var dd = parseInt(splitdate[0]);
            var mm = parseInt(splitdate[1]);
            var yy = parseInt(splitdate[2]);
            var ListofDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
            if (mm == 1 || mm > 2) 
            {
                if (dd > ListofDays[mm - 1]) 
                {
                    alert('Invalid date format!');
                    return false;
                }
            }
            if (mm == 2) 
            {
                var lyear = false;
                if ((!(yy % 4) && yy % 100) || !(yy % 400)) 
                {
                    lyear = true;
                }
                if ((lyear == false) && (dd >= 29)) 
                {
                    alert('Invalid date format!');
                    return false;
                }
                if ((lyear == true) && (dd > 29)) 
                {
                    alert('Invalid date format!');
                    return false;
                }
            }
        } 
        else 
        {
            alert("Invalid date format!");

            return false;
        }
    });
});

推荐阅读