首页 > 解决方案 > JavaScript 中的文本验证错误

问题描述

代码没有按我想要的方式工作。如果未填写登录名或密码字段,我编写了此代码以显示警报。但是,如果我填写登录信息并跳过密码,它不会按计划显示警报消息。任何帮助将不胜感激。

function check() {
  var x = document.forms['myform']['lid'].value;
  if (x == "") {
    alert("Please Enter the Login-Id")
    y = document.forms['myform']['pass'].value;
    if (y == "") {
      alert("The password field can't be blank")
    }
  }

}
body {
  background-color: lightblue;
  margin-left: 100px;
  margin-right: 100px;
}
<center>
  <h1> Welcome to X-mail.com </h1><br><br><br>
  <form name='myform'>
    Login-Id<input type="text" name='lid'> </input><br><br> Password
    <input type='password' name='pass'> </input><br><br><br>
    <button onclick="check()"> Login</button>
  </form>
  Don't have an account?
  <a href="signup.html"> Sign-Up </a>
</center>

标签: javascript

解决方案


您的检查功能逻辑似乎是嵌套的,这就是问题所在。正确的逻辑必须是

function check() {
            var x = document.forms['myform']['lid'].value;
            if (x == "") {
                alert("Please Enter the Login-Id")   
            }
            y = document.forms['myform']['pass'].value;
            if (y == "") {
                alert("The password field can't be blank")
            }

        }

推荐阅读