JavaScript表单onSubmit处理

时间:2013-02-11 05:49:03

标签: javascript onsubmit

我是JavaScript的新手,并且一直在搜索这里的线程,但无法弄清楚为什么我的表单没有正确运行验证。 我已经尝试添加警报来查找问题,看起来好像是在第一个IF语句周围。有任何想法吗?谢谢!

<script type="text/javascript">

function dataCheck()
{
        var firstName = document.getElementById("firstName").value;
        var firstName = document.myForm.firstName.value;
        var lastName = document.getElementById("lastName").value;
        var facilitator = document.getElementById("facilitator").value;
        //validate firstName field for minimum of 2 characters
        if (firstName.length < 2){
            alert("Please enter a first name with a minimum of 2 characters");
            return false;
        }
        else {retvalue = true}
        //validate lastName field for min length and numeric or alpha characters only
        if (lastName.length < 2 || lastName.){
            alert("Please enter a last name with a minimum of 2 characters");
            return false;
        }
        if( /[^a-zA-Z0-9]/.test(lastName) ) {
            alert("Last name must be alphanumeric.");
            return false;
        }
}

</script>

<form action="http://bucs601.com/submit.php" name="myForm" onsubmit="return dataCheck()" method="post">
              First name: <input type="text" id="firstName" name="firstName"><br>
              Last name: <input type="text" id="lastName" name="lastName"><br>
              Email: <input type="text" id="email" name="email"><br>
              Facilitator: <input type="text" id="facilitator" name="facilitator">
              <input type="submit" id="submit" value="Submit">
</form>

2 个答案:

答案 0 :(得分:1)

我能看到的一个明显错误是不完整的一行:

if (lastName.length < 2 || lastName.){

应该是第二个条件是什么?如果我删除“|| lastName”。位功能似乎正常。

答案 1 :(得分:0)

应该是这样的:

替换if (lastName.length < 2 || lastName.){

使用if (lastName.length < 2 || lastName){

删除.