简体   繁体   中英

Form submits despite of javascript validation returning false and displaying alert message

I have a form to be filled in by the users, and empty fields would prompt JavaScript validation to return a message to fill in that specific field. I'm able to accomplish this all except that in spite of returning an "Alert" message, the form gets submitted. How do I avoid this? Here's my JavaScript:

function validateHandAppr(theForm) {

    // Recom or Not Recom  
    if (document.project.rec.selectedIndex == 0) {
        alert("Please Choose the Recommendation Priority .");
        project.rec.focus();
        return false;
    }

    // Recommended priorities 
    if (document.project.rec.selectedIndex == 2 && document.project.recvd_dt.value == "") {

        alert("Fill in the date when culture was received.");
        project.recvd_dt.focus();
        return false;
    }

    if (document.project.rec.selectedIndex == 2 && document.project.recvd_by.value == "") {

        alert("Specify who received the culture.");
        project.recvd_by.focus();
        return false;
    }


    if (document.project.rec.selectedIndex == 2 && document.project.recvd_dt.value != "") {
        var validformat = /^\d{4}\-\d{2}\-\d{2}$/; //.test(project.recvd_dt.value) //Basic check for format validity

        if (!validformat.test(project.recvd_dt.value)) {
            alert("Invalid Date Format. Please enter in the following format: yyyy-mm-dd.")
            return false;
        } else { //Detailed check for valid date ranges
            var yearfield = project.recvd_dt.value.split("-")[0]
            var monthfield = project.recvd_dt.value.split("-")[1]
            var dayfield = project.recvd_dt.value.split("-")[2]
            var dayobj = new Date(yearfield, monthfield - 1, dayfield)
            if ((dayobj.getMonth() + 1 != monthfield) || (dayobj.getDate() != dayfield) || (dayobj.getFullYear() != yearfield)) {
                alert("Invalid Day, Month, or Year range detected. Please correct and submit again.")
                return false;
            } else {
                return true;
            }
        }
    }
}

Following is the form where JavaScript is being called:

<form accept-charset="UTF-8" id="project" name="project"
      action="hand_submit_forms.php" method="post"
      onSubmit="return validateHandAppr(this)"
      class="user-info-from-cookie" enctype="multipart/form-data">

Following is the updated code,as per suggested by DaveRandom:

      function validateHandAppr(theForm) {

  // Recom or Not Recom  
  //var val=true;
      if ( document.project.rec.selectedIndex == 0 )
       {
          alert ( "Please Choose the Recommendation Priority ." );
      document.project.rec.focus();
          return false;
        }



    // Recommended priorities 
       if ( document.project.rec.selectedIndex ==2 && document.project.recvd_dt.value == "")
       {

            alert("Fill in the date when culture was received.");
         document.project.recvd_dt.focus();
         return false; 
    }

       if ( document.project.rec.selectedIndex ==2 && document.project.recvd_by.value == "")
     {

  alert("Specify who received the culture.");
  document.project.recvd_by.focus();
  return false; 
  }


    if ( document.project.rec.selectedIndex ==2 && document.project.recvd_dt.value != ""){
        var validformat=/^\d{4}\-\d{2}\-\d{2}$/ ; //.test(project.recvd_dt.value) //Basic check for format validity

        if (!validformat.test(project.recvd_dt.value))
        {
        alert("Invalid Date Format. Please enter in the following format: yyyy-mm-dd.")
        return false;
        }
        else{ //Detailed check for valid date ranges
        var yearfield=project.recvd_dt.value.split("-")[0]
        var monthfield=project.recvd_dt.value.split("-")[1]
        var dayfield=project.recvd_dt.value.split("-")[2]
        var dayobj = new Date(yearfield, monthfield-1, dayfield)
        if ((dayobj.getMonth()+1!=monthfield)||(dayobj.getDate()!=dayfield)||(dayobj.getFullYear()!=yearfield))
        {
        alert("Invalid Day, Month, or Year range detected. Please correct and submit again.")
        return false;}
        else
        {
        return true; }
        }
    }

  //    return val;
      } 

The problem is these lines:

project.rec.focus();
// ...
project.recvd_dt.focus();
// ...
project.recvd_by.focus();

Your validation conditions reference document.project but the above lines represent simply project - which does not exist globally because it is a child of document , not window and you did not declare it locally.

Because these lines are between the alert() lines and the return false; lines, you will see the alert but the return statement will never be reached - so the function will not return false and the form will be submitted.

If you change the lines to:

document.project.rec.focus();
// ...
document.project.recvd_dt.focus();
// ...
document.project.recvd_by.focus();

...it should work.

However

You should assign the functions to the <form> s DOM object's submit event instead of using inline event handlers.

If you do this, you will be passed an event object to the first argument of the function, and you can use event.preventDefault() instead of returning false . This would avoid the problem (if the line was placed before the error occurred), and is generally a better way to handle this, because returning false also stops propagation of the event, which may not be desired - actually this makes little difference in this specific case but as a general rule it is true.

If you do this, the handler will be executed in the context of the DOM object - so the this variable will be a reference to it, and you won't need to pass it in as an argument.

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