即使验证失败,表单也会提交

时间:2012-08-03 01:14:02

标签: javascript

我只是在学习Javascript,所以如果我的问题看起来很傻,请耐心等待......

我需要创建一个html表单并在字段上运行一些验证。无论字段是否正确填充,我在按下提交按钮时都会收到错误404。如果我复制/粘贴其他人做同样事情的代码,它可以正常工作。文件“somepage.php”不存在,但对其他人的代码也不存在。

我在CodeLobster中编码,然后在Notepad ++中编码。没有变化。

这是HTML文件,下面是javascript文件的内容...

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>

    <head>
        <title>Registration Form</title>
        <script type="text/javascript" src="js.js"></script>
    </head>

    <body>
        <form action="somepage.php" onsubmit="checkLogin()" method="post" >

                Name: <input type="text" name="name" id="nameF" /><br />
                Email: <input type="text" name="email" id="emailF" /><br />

            <input type="submit" value="Submit" name="submit" />    

        </form>
    </body>

</html>

function checkLogin()
{
   var emailPattern = /^\w+([\.\-]?\w+)*@\w+([\.\-]?\w+)*\.[a-z]{2,6}$/i;
   var email = document.getElementById('emailF').value;
   var name = document.getElementById('name').value;    

    if (email == "")
    {
        alert("Please enter valid email address.");
       document.getElementById('emailF').select();
        document.getElementById('emailF').focus();
       return false;
    } else if   (name == "") {
        alert("Please enter your name.");
       document.getElementById('nameF').select();
        document.getElementById('nameF').focus();
       return false;
    }  else if (!emailPattern.test(email)) {
        alert("The email address entered is invalid");
       document.getElementById('emailF').select();
        document.getElementById('emailF').focus();
       return false;
    }
    return true;    
}

1 个答案:

答案 0 :(得分:5)

您的问题不在于页面丢失(您已经知道)。问题是您的表单无论如何都会提交,即使验证失败。

form.onsubmit方法应返回false以阻止表单提交。换句话说,这个:

<form action="somepage.php" onsubmit="checkLogin()" method="post" >

应该是:

<form action="somepage.php" onsubmit="return checkLogin()" method="post" >

当然,如果表单确实有效,它会正确地转到somepage.php,此时您会发现404错误,因为该页面不存在。

相关问题