如果正则表达式不匹配,我想在errors div中显示错误消息

时间:2013-10-28 22:09:48

标签: javascript jquery html regex

如果jquery匹配函数为false,我想向errors div添加errormessage

  <html>
  <head>
       <meta http-equiv="content-type" content="text/html; charset=UTF-8">
       <link href="form.css">

    </head>
    <body>
   <title>hw5</title>

    <form id ="myform" class = "myform">

        Date 1: <input type="text" name="date1" id="date1"value ="">(MM/DD/YYYY)              </input>
        <br/>
        Date 2: <input type="text" name="date2" id="date2"value = "">(MM/DD/YYYY)</input>
        <br/>
        <button id="calculate" class = "btn" >Calculate</button>


    </form>

    <div id="results" class = "results"> Please click on the calculate button above to retrieve a result.</div>
    <div id="errors" class = "errors" ></div>

<script src="jquery.js"></script>

<script type = "text/javascript">

        $(document).ready (function(){

            $("#myform").submit(function(){
                return false;
            });


            $("#calculate").click(function(){

                $('#myform').val().match(/^[0,1]?\d{1}\/(([0-2]?\d{1})|([3][0,1]{1}))\/(([1]{1}[9]{1}[9]{1}\d{1})|([2-9]{1}\d{3}))$/);



                var dataobj = {
                date1: $("#date1").val(),
                date2: $("#date2").val(),

                };

            $.ajax({
                url: 'calculate.php',
                data: dataobj,
                type: 'get',
                datatype: 'json',

                    success: function(serverResponse) {
                            alert(serverResponse);
                            $('#results').empty().text(serverResponse);
                    },
                    error: function (jqxhr, status, error) {
                            var friendlyErrorMessage = "An error occurred! - error     message: '" + error + "'";
                            $('#errors').empty().text(friendlyErrorMessage);
                    }
              });
            });
        });





 </script>



     </body>





      </html>

1 个答案:

答案 0 :(得分:0)

这有助于您在错误div上显示“无效日期”的错误

function validateDate(testdate) {
    var date_regex = /^(0[1-9]|1[0-2])\/(0[1-9]|1\d|2\d|3[01])\/(19|20)\d{2}$/ ;
    return date_regex.test(testdate); // can use return testdate.match(date_regex);
}

$("#calculate").click(function(){

    if(!(validateDate($('#date1').val())) || !(validateDate($('#date2').val()))) {
        var friendlyErrorMessage = "Invalid Date";
        $('#errors').empty().text(friendlyErrorMessage);
        return false;
    }

    //Rest of code to send ajax request.
}