日期格式的正则表达式MM / DD / YYYY返回错误结果

时间:2016-04-30 12:28:39

标签: javascript jquery regex

每次点击我的文本框(prfm_dtrequest)时,我都会弹出一个jquery日期选择器。它返回mm / dd / yyyy格式,这是我想要的方式。我需要在之后验证文本框的内容,以确保在单击提交按钮(#submitform)之前将其加载到我的数据库中之前格式正确。我的代码只返回“即使我

”也不是“有效日期”
    <!DOCTYPE html>
    <html lang="en">
        <head>
            <title>testing</title>
              <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
              <script src="//code.jquery.com/jquery-1.10.2.js"></script>
              <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
              <link rel="stylesheet" href="/resources/demos/style.css">
             <script>
              $(function() {
                $( "#prfm_dtrequest" ).datepicker();
              });
            </script>
            <script>
                $(document).ready(function(){
                $("#submitform").click(function(){
                    var daterequested = $("#prfm_dtrequest").val();
                      var dateMMDDYYYRegex = /^(0[1-9]|1[0-2])\/(0[1-9]|1\d|2\d|3[01])\/(19|20)\d{2}$/ ;
                        if(dateMMDDYYYRegex.test(dateMMDDYYYRegex)){
                           alert('is a valid date: '+daterequested);
                        }else{
                           alert('is not a valid date: '+daterequested);
                        }
                });
            });
            </script>
        </head>
        <meta charset="utf-8">
        <body>
            <form method='post' action=''>
                <input type="date" id="prfm_dtrequest" class='txtfld01' name=''><input type="submit" id="submitform" value="submit">
            </form>
        </body>
    </html>

2 个答案:

答案 0 :(得分:1)

请更正您的正则表达式(有效日期示例: 03/31/1988 ):

$(document).ready(function(){
    $("#submitform").click(function(){

    /* isValidData source: http://stackoverflow.com/questions/5812220/how-to-validate-a-date */

    function isValidDate(s) {
       var bits = s.split('/');
       var d = new Date(bits[2], bits[0] - 1, bits[1]);
       return d && (d.getMonth() + 1) == bits[0] && d.getDate() == Number(bits[1]);
    }

    var daterequested = $("#prfm_dtrequest").val();
        var dateMMDDYYYRegex = "^[0-9]{2}/[0-9]{2}/[0-9]{4}$";
        if(daterequested.match(dateMMDDYYYRegex) && isValidDate(daterequested)){
            alert('is a valid date: '+daterequested);
        }else{
            alert('is not a valid date: '+daterequested);
        }
    });
});

Demo

结果:

enter image description here

答案 1 :(得分:-1)

在mm / dd / yyyy格式下使用以下正则表达式:

    var dateMMDDYYYRegex = /^(0[1-9]|1[0-2])\/(0[1-9]|1\d|2\d|3[01])\/(19|20)\d{2}$/ ;
    if(dateMMDDYYYRegex.test(dateMMDDYYYRegex)){
       alert('is a valid date: '+daterequested);
    }else{
       alert('is not a valid date: '+daterequested);
    }