简体   繁体   中英

Form Validation doesn't validate for Password

I can't see what's wrong. When I try to validate email it works fine, but it doesn't check for the password at all! It's literally the simplest a program can get.

    function validateForm() {
        var email = document.forms["myForm"]["email"].value;
        var password = document.forms["myForm"]["password"].value;

        if (email == "") {
            alert("Email must be filled out");
            document.getElementById("emailE").innerHTML = "<font color=\"red\"> Pls fill in email.</font>";
            return false;
        }

        else if (password == "" && password.length > 8) {
            alert("Password must be filled out");
            document.getElementById("passwordE").innerHTML = "<font color=\"red\"> Pls fill in password and it should be greater than 8 chars.</font>";
            return false;
        }
    }
</script>
</head>
<body>
    <h1>School Form</h1>

    <form name="myForm" action="/action_page.php"
        onsubmit="return validateForm()" method="post">
        <table cellspacing="10">
            <tr>
                <th>Email:</th>
                <th><input type="email" name="email"></th>
                <th><span id="emailE"></span></th>
            </tr>
            <tr>
                <th>Password:</th>
                <th><input type="password" name="password"></th>
                <th><span id="passwordE"></span></th>
            </tr>
        </table>
        <input type="submit" value="Submit">

    </form>
</body>
</html>```

You are checking the email and not password because once the first if statement is true it will not go to the else if of the same block so use them in different blocks of if else statement or use both of them in one if statement

secondly you are checking for the length of password is more than 8 and its value is '' so this is impossible to have.

Here are some suggestions

  1. Font tag is depreciated a long ago so don't use this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM