0

我有一个更改密码的表单,对所有表单字段进行 javascript 验证检查,但是,我认为 Javascript 甚至不会被触发。输入提交将我直接带到我的控制器中的空指针异常错误。我错过了什么吗?

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Change Password Page</title>    
    <script type="text/javascript">
        function validate(){

            var username=document.form.j_username.value;
            var oldPassword=document.form.j_old_password.value;
            var newPassword=document.form.j_new_password.value;
            var confirmPassword=document.form.j_confirm_password.value;

            if(username==""){
             alert("Enter Username!");
              return false;
                }

            if(oldPassword==""){
             alert("Enter Old Password!");
              return false;
                }

            if(newPassword==""){
                 alert("Enter New Password!");
                  return false;
                }

            if(confirmPassword==""){
                 alert("Enter Confirm Password!");
                  return false;
                }

            return true;

        }       
    </script>
</head>

<body>
    <div class="change_password-header">
    <h1>Blah Blah</h1>
    </div>
    <div class="L" style="float: left; left; padding: 1em; background-color: #8eb4e3; border: 1px solid black;">
    <form action="changepassword" method="post" onsubmit="return validate()">
        <p><strong style="color: #e3f7ff">Username: </strong>
            &nbsp;<input type="text" name="j_username" size="25" />
        </p>

        <p><strong style="color: #e3f7ff">Old Password: </strong>
            &nbsp;<input type="password" size="25" name="j_old_password" />
        </p>

        <p><strong style="color: #e3f7ff">New Password: </strong>
            &nbsp;<input type="password" size="25" name="j_new_password" />
        </p>

        <p><strong style="color: #e3f7ff">Confirm New Password: </strong>
            &nbsp;<input type="password" size="25" name="j_confirm_password" />
        </p>

        <div style="text-align: center;">
            <input type="submit" value="Submit" class="button-login" style="background-color: #c7d9f1; border: 1px solid black;" />
            <input type="reset" value="Reset" class="button-login" style="background-color: #c7d9f1; border: 1px solid black;"/>
        </div>
    </form>
    </div>

    <div style="float: left; width: 100%; font-size: 12px; padding: 0 0 0 2em" class="change_password-footer">
        <div><a href = "login">Return back to login screen</a></div>
        <br/>
    </div>  
</body>
</html>
4

1 回答 1

1

您只是忘记命名您的表单:

<form action="changepassword" name="test" method="post" onsubmit="return validate()">

并像这样在JS中引用:

var username=document.forms.test.j_username.value;

http://jsfiddle.net/gq79y/

于 2013-04-05T19:11:17.697 回答