【问题标题】:How to make validation on date after adding the automatically slash?添加自动斜线后如何进行日期验证?
【发布时间】:2018-04-19 11:07:13
【问题描述】:

我有一个文本字段。如果任何用户输入日期,它将自动在其上添加斜杠,但问题是它也接受 60/60/6060。 它也接受字符。你能帮我验证一下吗?

$(document).ready(function(){  
            $("#txtDate").keyup(function(e){
                if (e.keyCode != 8){    
                    if ($(this).val().length == 2){
                        $(this).val($(this).val() + "/");
                    }else if ($(this).val().length == 5){
                        $(this).val($(this).val() + "/");
                    }
                }
            });   
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input type="text" name="date"  placeholder="date (dd/mm/yy)" maxlength=10 id="txtDate">

【问题讨论】:

    标签: javascript jquery html validation date


    【解决方案1】:

    您可以使用 checkdate($mth,$day,$yr) 或正则表达式来验证日期。

    /(0\d{1}|1[0-2])\/([0-2]\d{1}|3[0-1])\/(19|20)\d{2}/
    
    
    $(document).ready(function () {
            $("#txtDate").keyup(function (e) {
                if (e.keyCode != 8) {
    
                    if ($(this).val().length == 2) {
                        $(this).val($(this).val() + "/");
                    } else if ($(this).val().length == 5) {
                        $(this).val($(this).val() + "/");
                    }
    
                }
            });
    
            //below will clear the textbox onblur if invalid date entered
            $("#txtDate").blur(function () {
                var reg = /(0\d{1}|1[0-2])\/([0-2]\d{1}|3[0-1])\/(19|20)\d{2}/;
                if (!reg.test($("#txtDate").val())) {
                    // clear box if invalid
                    $("#txtDate").val("");
                }
            });
        });
    

    【讨论】:

    • 感谢您的回复。但是我应该在哪里使用它
    • 它解决了几乎 90% 的问题。只是想知道。能不能把$("#txtDate").val("")的$("#txtDate").html("Invalid date")设置成;这样理解起来会更清楚。
    • 是的,根据您的要求,您可以在文本框或任何标签上设置值以显示该验证消息。
    猜你喜欢
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 2013-05-05
    • 2018-06-06
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    相关资源
    最近更新 更多