0

如果 jquery 匹配函数为 false,我想向错误 div 添加错误消息

  <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>
4

1 回答 1

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.
}
于 2013-10-28T22:51:15.550 回答