如何修复 JavaScript 的登录验证?

How can I fix my Login validation for JavaScript?

我正在尝试对我的登录表单进行基本验证,但它似乎不起作用。

这是我的代码: 脚本:

var attempt = 3; // Variable to count number of attempts.
// Below function Executes on click of login button.
function validate(){
    var email = document.getElementById("email").value;
    var password = document.getElementById("password").value;
    if ( email == "admin@gmail.com" && password == "1234"){
        alert ("Login successfully");
        window.location = "success.html"; // Redirecting to other page.
        return false;
    }
    else{
        attempt --;// Decrementing by one.
        alert("You have left "+attempt+" attempt;");
// Disabling fields after 3 attempts.
        if( attempt == 0){
            document.getElementById("username").disabled = true;
            document.getElementById("password").disabled = true;
            document.getElementById("submit").disabled = true;
            return false;
        }
    }
}

HTML:

<form>
                    <div class="form-group">
                        <label for="exampleInputEmail1">Email address</label>
                        <input type="email" class="form-control" name="email" aria-describedby="emailHelp" placeholder="Enter email">
                        <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
                    </div>
                    <div class="form-group">
                        <label for="exampleInputPassword1">Password</label>
                        <input type="password" class="form-control" name="password" placeholder="Password">
                    </div>
                    <div class="form-group form-check">
                        <input type="checkbox" class="form-check-input" id="exampleCheck1">
                        <label class="form-check-label" for="exampleCheck1">Check me out</label>
                    </div>
                    <button type="submit" class="btn btn-primary">Submit</button>
                </form>

P.S。我已将脚本文档包含在我的 HTML 页面中。

您需要将验证函数绑定到某物。假设您想要将它绑定到提交按钮,它看起来像这样。

document.getElementsByTagName("button").addEventListener("click", validate );