0

我有一个要由用户填写的表单,空字段会提示 JavaScript 验证返回一条消息以填写该特定字段。我能够完成这一切,除了尽管返回“警报”消息,表单被提交。我该如何避免这种情况?这是我的 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;
            }
        }
    }
}

以下是调用 JavaScript 的形式:

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

以下是根据 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;
      } 
4

1 回答 1

0

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.

于 2013-01-03T12:03:34.773 回答