是否遇到过这么个需求,一个需要输入日期的地方,但是用户要求说就是不想用datepicker控件,不想用鼠标去点,就想直接输入数字。

在这里直接自己手写了一份jquery的验证代码,此代码实现了自动填充横杠、自动补日月的0,保持yyyy-MM-dd格式,失去焦点和输入完毕时的日期验证功能。

例如实现2018-10-08,使用这套规则只需输入20181008、2018108即可。

if ($(this).attr("directinput") == "1") {
    //变更事件
    $(this).bind("keyup", function (e) {
        //如果是退格键,则不校验。
        if (e.which == 8) { return; }

        //如果输入到月份,输入后的月份大于12,则在两个数的中间加一个-号
        if ($(this).val().split("-").length == 2 && $(this).val().split("-")[1] != "") {
            var month = $(this).val().split("-")[1];
            if (parseInt(month) > 12) {
                var resultVal = $(this).val().split("-")[0] + "-" + month.substring(0, 1) + "-" + month.substring(1); 
                $(this).val(resultVal);
            }
        }

        //第5位、第8位自动补横杠
        if (($(this).val().length == 4 || $(this).val().length == 7) && $(this).val().split("-").length - 1 < 2) { $(this).val($(this).val() + "-"); } //输入共10个字符,并且验证日期不合法,则失去焦点时提示。 if ($(this).val().length == 10 && !(new Date($(this).val()).getDate() == $(this).val().substring($(this).val().length - 2))) { alert("输入的日期不合法,请重新输入。"); $(this).val(""); } //如果存在2个杠,且长度在8、9,验证年月日的长度,把0位补足 if ( ( ($(this).val().length == 8 || $(this).val().length == 9) && $(this).val().split("-").length == 3 && $(this).val().lastIndexOf("-") != $(this).val().length - 1 && $(this).val().lastIndexOf("0") != $(this).val().length - 1 ) || $(this).val().length > 10) {
            var splitval = $(this).val().split("-");
            var result = "";

            //年不满4位则直接报错
            if (splitval[0].length < 4) {
                alert("输入的日期不合法,请重新输入。");
                $(this).val("");
            } else {
                //规范化日期格式,并进行最后校验
                result = splitval[0];
                result += "-";

                var val1 = parseInt(splitval[1]);
                if (val1 < 10) {
                    result += "0" + val1;
                } else {
                    result += val1;
                }
                result += "-";

                var val2 = parseInt(splitval[2]);
                if (val2 < 10) {
                    result += "0" + val2;
                } else {
                    result += val2;
                }
                $(this).val(result);

                if (!(new Date($(this).val()).getDate() == $(this).val().substring($(this).val().length - 2))) {
                    alert("输入的日期不合法,请重新输入。");
                    $(this).val("");
                }
            }
        }
    });

    //失去焦点时验证日期合法性
    $(this).bind("blur", function () {
        if ($(this).val() != "" && !(new Date($(this).val()).getDate() == $(this).val().substring($(this).val().length - 2))) {
            alert("输入的日期不合法,请重新输入。");
            $(this).val("");
            $(this).focus();
        }
    });
}