如何修复JavaScript的登录验证?

时间:2019-02-25 19:29:15

标签: javascript java html validation login

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

这是我的代码: 脚本:

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页面中。

1 个答案:

答案 0 :(得分:0)

您需要将validate函数绑定到某些东西。假设您希望将其绑定到“提交”按钮,它将看起来像这样。

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