所有浏览器似乎都忽略了JavaScript客户端表单验证规则

时间:2014-03-25 17:26:24

标签: javascript html validation

我已经使用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>   

**请注意,我还尝试将return true部分放在else语句中:

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

我错过了什么吗? 感谢

1 个答案:

答案 0 :(得分: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);