简体   繁体   中英

I want display an error message in the errors div if the regexp doesnt match

i want to add an errormessage to the errors div if the jquery match function is false

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

This will help you to display the error for "invalid date" on errors 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.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM