2014-03-25 41 views
0

我已經使用JavaScript來確保我的表單上的字段被正確填寫(具有正確類型的信息的必填字段),並且瀏覽器似乎忽略了我設置的規則並且無論如何處理信息。所有瀏覽器似乎忽略JavaScript客戶端表單驗證規則

HTML

HTML 



<form id="course-form" name="courseForm" method="POST" onSubmit="return checkCourse()" action="#"> 
     <label for="courseName">Course Name: </label> 
     <input type="text" id="course-name" name="courseName" placeholder="Course Name" required/><br/> 
     <br> 
     <label for="qualDesc">Description: </label><br/> 
     <textarea name="qualDesc" class="boxsizingBorder" placehold 
     <label for="entryReqs">Entry Requirements</label><br> 
     <textarea name="entryReqs" class="boxsizingBorder" id="entry-reqs" placeholder="Previous Grades Required" required></textarea><br> 
     <br> 
     <label for="cost">Cost: &pound;</label> 
     <input type="text" name="cost" id="courseCost" maxlength="6" size="5" required/><br> 
     <br> 
     <input type="submit" value="Add Course" /> 
</form> 

的JavaScript(放置在文件頭)

 <script> 
     function checkCourse() 
     { 
      var date = new Date(); 
      var year = (date.getFullYear());    
      var courseName=document.forms["courseForm"]["courseName"].value; 
      var courseDesc=document.forms["courseForm"]["qualDesc"].value; 
      var courseYear=document.forms["courseForm"]["year"].value; 
      var entryReqs=document.forms["courseForm"]["entryReqs"].value; 
      var cost=document.forms["courseForm"]["cost"].value; 

      if(courseName == "") 
      { 
       alert("Course name is a required field."); 
       return false; 
      } 
      else if(courseDesc=="") 
      { 
       alert("The Course needs a description"); 
       return false; 
      } 
      else if(courseYear < year) 
      { 
       alert("The academic year for " + courseYear + " has already commenced. \n Please pick a later date); 
       return false; 
      } 
      else if(entryReqs=="") 
      { 
       alert("You must enter some entry requirements"); 
       return false; 
      } 
      else if(isNaN(cost) || (cost=="")) 
      { 
       alert("Cost is not a valid numerical figure"); 
      } 

      alert("Course added sucessfully!"); 
      return true; 

     } 
    </script> 

**注意,我也嘗試過把真正的收益部分中像這樣的else語句:

else 
{ 
    alert("Course added sucessfully!"); 
    return true; 
} 

我錯過了什麼嗎? 謝謝

回答

2

在下面一行中,您嘗試獲取輸入值,但您的表單不包含名爲year的輸入。這將導致一個JavaScript錯誤,隨後,您的驗證將被忽略,表格將繼續提交

var courseYear=document.forms["courseForm"]["year"].value; 

的第二個問題是你不return false如果成本驗證失敗(但這不是你的根本問題)。

另外,作爲juvian指出,你錯過下面的警報收盤報價:

alert("The academic year for " + courseYear + " has already commenced. \n Please pick a later date); 
+1

啊,他也缺少了「警報 – juvian

+0

好去處,加入到回答 – MrCode

+0

另外,HTML是無效,一個打開的textarea沒有關閉: