JavaScript未通过表单验证执行

JavaScript not executing with form validation

本文关键字:验证 执行 表单 JavaScript      更新时间:2023-09-26

我对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>

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

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

试试这个:

   <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>

validate函数中,需要将LoginInformationusernamepassword用引号括起来。如果不是,您的JavaScript解释器会将它们视为常规的ol'JavaScript变量,而事实并非如此。