HTML表单客户端验证

时间:2014-03-29 03:03:47

标签: javascript html validation client

我对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>  

1 个答案:

答案 0 :(得分:0)

正如评论者所说,当您将代码移动到文档的<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事件绑定到输入,这样当您从密码输入移动到密码确认输入时,您将看到记录(您可以忽略这一点,因为您赢了&#39;尚未输入确认密码)。

最后,值得注意的是,Firefox在用户反馈方面与Chrome的行为略有不同;当您键入时,Firefox会在有问题的文本输入周围发出红光,当密码确认输入中输入的密码相同时,它会消失。 Chrome不会执行此操作,只会在您单击提交按钮后指示密码不匹配。