简体   繁体   English

Javascript 表单验证可能不起作用

[英]Javascript form validation didn't work probably

I know this is stupid but i don't know why my validation function doesn't work.我知道这很愚蠢,但我不知道为什么我的验证功能不起作用。 It keeps blinking "Need to fill both input !!!"它一直闪烁“需要填写两个输入!!!” . . Pls help me请帮助我

Here is my code:这是我的代码:

<div class="container">
  <h2>Login form</h2>
  <form action="signin.php" method="POST" onsubmit="return validation();">
    <h3 id='error'></h3>
    <div class="form-group">
      <label>Username:</label>
      <input name="username" type="text" class="form-control" id="userName" placeholder="Enter username">
    </div>
    <div class="form-group">
      <label>Password:</label>
      <input name="password" type="password" class="form-control" id="password" placeholder="Enter password">
    </div>
    <div class="checkbox">
      <label><input type="checkbox" name="remember"> Remember me</label>
    </div>
    <button name="login" type="submit" class="btn btn-default">Submit</button>
  </form>
</div>
function validation(){
    var username = document.getElementById('userName').value;
    var password = document.getElementById('password').value;
    var error = document.getElementById('error');
    if(username === "" || password === ""){
        error.innerHTML="Need to fill both input !!!"
        setTimeout(()=>error.remove(),3000);
        return false;
    }
    return true;
}

As stated in comments, the first time validation happens, you remove your error element.如评论中所述,第一次验证发生时,您删除error元素。 It finishes fine, but with dire consequences.它完成得很好,但后果很严重。 The second time validation happens, document.getElementById('error') will give you undefined , causing error.innerHTML= to fail, which means the function does not return false or prevent default, so the submit event is free to continue unimpeded.第二次验证发生时, document.getElementById('error')会给你undefined ,导致error.innerHTML=失败,这意味着该函数不会返回false或阻止默认,因此submit事件可以不受阻碍地继续进行。

Instead of removing error , empty it (the same way you filled it is fine).与其删除error不如清空它(与填充它的方式相同)。

setTimeout(() => error.innerHTML = "", 3000);

Probably you have misspelling in可能你拼错了

getElementById('user**N**ame')

It should be in lowercase - username它应该是lowercase - 用户名

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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