javascript - 如何在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>
解决方案
错误在于,在您的表单 html 元素中,您正在调用 onclick 事件,该事件在您单击任何 html 元素时执行,因此传递值和 confpass 值是未定义的,直到您更改其中之一,这就是您看到警报的原因。解决方案:使用 onsubmit 事件。
<form action="insert.php" method="POST" onsubmit="return validation();">
推荐阅读
- highcharts - Highchart,如何在中间垂直对齐一条线?
- excel - 通过递增到 Excel 中的特定行来获取价值
- excel - 仅当不同的单元格在一系列数据中出现故障时,如何显示单元格?
- sql - SQL - 关于 Salesforce 表的问题 - 将事件与任务链接
- javascript - 根据文本内容重新排列 DOM 元素
- angular - Angular - 如何正确更改选项卡单击上的动态生成视图?
- c# - 有什么方法可以使用自定义标签来忽略 Specflow 中的正确测试
- python - 相当于 kubectl get pods 的 Python Kubernetes 客户端
- jquery - RShiny:为 tabsetPanel 中具有随机生成的 ID 的 UI 项检索 jsQuery 选择器
- android - 如何在 pexels API 中的 Flutter 图像中设置壁纸