0

它不返回 false 并且不显示错误。见 jfiddle http://jsfiddle.net/paYap/2/

我的JavaScipt:

function validateForm() {
    var error = "";
    var x=document.getElementById('fname').value;
    var y=document.getElementById('lname').value;
    /*  
    Additional variable defined here, commented out for debugging
    */
    if ((x==null || x=="") || (y==null || y==""))
      {
      error += "-First and last name required. <br />";
      }
      /*
      There were additional statements here, commented out for debugging
     */
    if (error != ""){
      alert(error);
      //document.getElementById('error').innerHTML = "Error: " + error;
      return false;
    }
}

我也附上onsubmit="return validateForm()"了表格。

有人可以帮我看看并告诉我是否遗漏了什么吗?

4

1 回答 1

3

您实际上可能没有返回false,您可能会返回,因为如果验证通过undefined,您不会返回。true

这会诱使您认为您的验证是正确的,而事实并非如此。

添加return true;到函数的末尾可能证明您毕竟没有返回 false。

function validateForm() {
    var error = "";
    var x=document.getElementById('fname').value;
    var y=document.getElementById('lname').value;
    /*  
    Additional variable defined here, commented out for debugging
    */
    if ((x==null || x=="") || (y==null || y==""))
      {
      error += "-First and last name required. <br />";
      }
      /*
      There were additional statements here, commented out for debugging
     */
    if (error != ""){
      alert(error);
      //document.getElementById('error').innerHTML = "Error: " + error;
      return false;
    }

    alert("Actually, returning true!");
    return true;
}
于 2012-10-29T22:53:27.863 回答