JavaScript表单验证不检查错误

时间:2014-09-04 20:39:08

标签: javascript php validation

我在php文件的头部有这个JavaScript代码:

<script language="JavaScript" type="text/javascript">
        function validateFirstName(field)
        {
            if (field == "")
            {
                return "Please enter a first name.\n";
            }
            else if (/[^a-zA-Z]/.test(field))
            {
                return "Invalid first name.\n";
            }
            return "";
        }
        function validateLastName(field)
        {
            if (field == "")
            {
                return "Please enter a last name.\n";
            }
            else if (/[^a-zA-Z]/.test(field))
            {
                return "Invalid last name.\n";
            }
            return "";
        }
        //more functions eliminated
        function validate(form)
        {
            fail = validateFirstName(form.firstname.value);
            fail += validateLastName(form.lastname.value);
            //and so forth

            if (fail == "")
            {
                return true;
            }
            else
            {
                alert(fail);
                return false;
            }
        }
    </script>

形式:

<form action="StudentSignUpPageAddingData.php" method="post" onsubmit="return validate(this)">
    <p id="p3">First Name: <input id="roundedcorners" type="text" name="firstname"><br></p>
    <p id="p3">Last Name: <input id="roundedcorners" type="text" name="lastname"><br></p>
//and so forth
    <input id="i1" type="submit" value="Done!">
</form>

但是,当我运行它时,程序会跳到StudentSignUpPageAddingData.php中的代码。我是PHP和JavaScript的新手,所以我想知道onsubmit调用是否有问题。我是否还应该考虑将JavaScript代码粘贴到单独的文件中并简单地在PHP文件中引用它?

1 个答案:

答案 0 :(得分:0)

知道了,原来我的计算机因某种原因禁用了JavaScript。这是一个快速链接,可以找出如何快速启用JavaScript:

http://activatejavascript.org/en/instructions/safari