首页 > 解决方案 > 如何在html中验证密码

问题描述

这是我的注册页面的 html 代码,但我无法验证密码字段。这里发生的情况是,每当我输入密码并单击确认密码时,它都会显示错误消息,甚至不允许我再次输入密码。请帮我解决这个问题!谢谢!

<!DOCTYPE html>
<html>
<head>
    <title>Sign up form</title>
    <link rel="stylesheet" type="text/css" href="signup.css">
</head>
<body>
    <div class="signup">

            <form action="insert.php" method="POST" onclick="return validation();">
                  <div id="eresult" style="color: red;"></div>
        <p>Username</p>
            <input type="text" name="username" placeholder="Enter New Username" required id="name">
            <p>Email</p>
            <input type="Email" name="email" placeholder="Enter Email" required id="email">
            <p>Password</p>
            <input type="password" name="pass" placeholder="Enter Password" required id="pass">
            <p>Confirm Password</p>
            <input type="password" name="confpass" placeholder="Confirm Password" required id="confpass">
            <input type="submit" name="" value="Submit">

        </form>
    </div>

      <script type="text/javascript">
      function validation(){
            var name = document.getElementById('name').value;
            var email= document.getElementById('email').value;
            var password = document.getElementById('pass').value;
            var confpassword = document.getElementById('confpass').value;

            if(password == confpassword){
                  return true;

            }
            else{
                  alert("Password does not match!!");

                  return false;
            }
      }

      </script>
</body>
</html>

标签: javascripthtmlformsvalidation

解决方案


错误在于,在您的表单 html 元素中,您正在调用 onclick 事件,该事件在您单击任何 html 元素时执行,因此传递值和 confpass 值是未定义的,直到您更改其中之一,这就是您看到警报的原因。解决方案:使用 onsubmit 事件。

<form action="insert.php" method="POST" onsubmit="return validation();">

推荐阅读