JavaScript没有执行表单验证

时间:2014-05-01 18:23:10

标签: javascript html web

我对Web开发相对较新,我正在尝试使用javascript进行一些表单验证,但我的javascript块没有执行,我真的不知道为什么。有什么想法吗?

<html>
<head>
    <title>Login</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link type = "text/css" rel = "stylesheet" href = "formato.css" />
    <script type = "text/javascript">
        function validate(){
            var x = document.forms[LoginInformation][username].value;
            var y = document.forms[LoginInformation][password].value;
            if(document.LoginInformation){
                alert("Enter a username");
                return false;
            }
            if(y===null || x ===""){
                alert("Enter a password");
                return false;
            }
        }
    </script>
</head>
<body>
    <center>
        <div id = "login">

        <form method = "post" name = "LoginInformation" onsubmit = "return (validate());" action="./TestLogin">
            <fieldset>
                <legend>Informaci&oacute;n de Login</legend>
                <label>Usuario:<br />
                <input type="text" name="username" size ="15"/></label><br /> 
                <label>Contrase&ntilde;a:<br />
                <input type="password" name="password" size ="15"/></label><br />
                <label><br /><input type = "submit" name = "login" value = "Login"/></label><br />
            </fieldset>
        </form>
        </div>
    </center>
</body>

3 个答案:

答案 0 :(得分:1)

请将表单ID和控件ID作为字符串传递,如下所述

var x = document.forms["LoginInformation"]["username"].value; var y = document.forms["LoginInformation"]["password"].value;

答案 1 :(得分:0)

试试这个:

   <script type = "text/javascript">
    function validate(){
        var x = document.getElementbyID("username");
        var y = document.getElementbyID("password");
        if(x==""){
            alert("Enter a username");
            return false;
        }
        if(y==null || x ==""){
            alert("Enter a password");
            return false;
        }
     }
   </script>

然后你在

之间编码
<form method="post" name="LoginInformation" action="./TestLogin">
        <fieldset>
            <legend>Informaci&oacute;n de Login</legend>
            <label>Usuario:<br />
            <input type="text" id="username" size ="15"/></label><br /> 
            <label>Contrase&ntilde;a:<br />
            <input type="password" id="password" size ="15"/></label><br />
            <label><br /><input type ="submit" name ="login" value = "Login" onClick="validate()"/></label><br />
        </fieldset>
    </form>

答案 2 :(得分:0)

validate功能中,您需要将LoginInformationusernamepassword括在引号中。如果不是,那么您的JavaScript解释器会将它们视为常规的&#39; JavaScript变量,它们不是。