2014-03-29 163 views
1

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

 <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> 
+0

你能显示你的完整的html和js代码吗? –

+0

这是我的整个JS代码,我做了一切在HTML – calixProg

+0

移动你的形式和脚本正文。为我工作得很好。 (在firefox24和chrome33上测试) – anu

回答

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事件绑定到输入,所以当您从密码输入移动到密码确认输入时,您会看到日志记录(因为您尚未输入确认密码,您可以忽略此事件)。

最后,值得注意的是,Firefox在用户反馈方面的表现与Chrome略有不同;键入时,Firefox会在输入的文本输入附近放一个红色的光,当输入的密码确认输入中的密码相同时,消失。 Chrome不会这样做,只会在单击“提交”按钮后指出密码不匹配。