2014-03-29 215 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不會這樣做,只會在單擊「提交」按鈕後指出密碼不匹配。