HTML表单客户端验证

HTML FORM CLIENT VALIDATION

本文关键字:验证 客户端 表单 HTML      更新时间:2023-09-26

我是javascript场景的新手,更不用说在rails应用程序上使用它了。所以我决定做一个客户端验证我的注册形式一切工作正常,但我的脚本检查密码是否匹配确认密码。每次它告诉我密码不匹配,我真的希望有人能帮我这个。提前感谢:)P.S这主要是html和javascript

     <head>
    <form id="sign_up" method="post" action="/auth/identity/register">   
      <div class="field"> 
        <input id="name" class="username" type="text" placeholder="Full name" name="name" required></input>
     </div>
     <div class="field"> 
        <input id="email" class="username" type="email" placeholder="Email address" name="email" required></input>
     </div>
     <div class="field"> 
        <input id="password" class="username" type="password" placeholder="Password" name="password" required></input>
    </div>
    <div class="field"> 
    <input id="password_confirmation" class="username" type="password" placeholder="Password confirmation" name="password_confirmation" required></input>
    </div>
      <div class="field"> 
        <input class="btn btn-primary" type="submit" value="Sign up" name="commit"></input>
      </div>
     </form>
<script type="text/javascript">
window.onload = function () {
    document.getElementById("password").onchange = validatePassword;
    document.getElementById("password_confirmation").onchange = validatePassword;
}
function validatePassword(){
var pass2=document.getElementById("password_confirmation").value;
var pass1=document.getElementById("password").value;
if(pass1!=pass2){
    document.getElementById("password_confirmation").setCustomValidity("Passwords Don't Match");
}
else
    document.getElementById("password_confirmation").setCustomValidity(''); 
//empty string means no validation error
}
</script>
  </div>
</head>  

正如评论者所说,当您将代码移动到文档的<body>中时,它就可以工作了。也许在文档中有多个ID为passwordpassword_confirmation的元素?

如果没有,我将首先记录输入的密码和password_confirmation值,即:
console.log("Password box value: "+pass1);
console.log("Password confirmation box value: "+pass2);

把这些行放在var pass1=document.getElementById("password").value;

下面

然后您可以在浏览器控制台(F12键)中直观地检查输入的值,以确保它们是相同的。在单击提交按钮后检查这些值。请记住,您将onchange事件绑定到输入,因此当您从密码输入移动到密码确认输入时,您将看到日志记录(您可以忽略这一点,因为您还没有输入确认密码)。

最后,值得注意的是,Firefox在用户反馈方面与Chrome略有不同;当你输入错误的文本时,Firefox会在文本周围显示红光,当在密码确认输入中输入的密码相同时,红光就会消失。Chrome不会这样做,只会在你点击提交按钮后提示密码不匹配。