2013-05-29 174 views
0

我想驗證密碼字段使用JavaScript。確保用戶在確認密碼字段中重新輸入密碼時,它應該是相同的。驗證確認密碼?

這是我試圖做的。這是表格。 onsubmit =「validate_reg()」是另一種使用javascript進行驗證以確保所有字段都必須填寫。

<form name="register" action="signup.php" onsubmit="return validate_reg()"enctype="multipart/form-data" method="post" > 
<table width="600" border="0"> 
<tr><td width="210" height="45">Username*:</td><td> 
<input type="text" size="40" name="userUsername" id="user_username" /></td></tr> 
<tr><td width="210" height="45">Password*:</td><td> 
<input type="password" size="40" name="userPassword" id="user_password"/></td></tr> 
    <tr><td width="210" height="45">Re-type Password:</td><td> 
<input type="password" size="40" name="userPasswordConfirm" 
    id="user_password_confirm"/></td></tr> 
</table> 
</form> 

這是JavaScript代碼:

<!--================Javascript for the validation of the Password Confirmation==========================--> 
<script type="text/javascript" language="javascript"> 

function validatepw() { 
    if (document.register.user_password.value != document.register.user_password_confirm.value) 
    { 
    alert('Passwords did not match!'); 
     return false; 
     }else{ 
     document.register.submit(); 
     return true; 
    } 
    } 
</script> 

<!--================Javascript for the validation of the required fields ================================--> 
<script type="text/javascript"> 

    function validate_reg() 
    { 
    var isValid = true; 

    // using OLD method of using name to find the control 

    if (document.register.user_username.value == "") 
    { 
    document.register.user_username.style.backgroundColor="red"; 
    isValid=false; 
    } 
    else{ 
    document.register.user_username.style.backgroundColor="white"; 
    } 
    if (document.register.user_password.value == "") 
    { 
    document.register.user_password.style.backgroundColor="red"; 
    isValid=false; 
    } 
    else{ 
    document.register.user_password.style.backgroundColor="white"; 
    } 
    if (document.register.user_password_confirm.value == "") 
    { 
    document.register.user_password_confirm.style.backgroundColor="red"; 
    isValid=false; 
    } 
    else{ 
    document.register.user_password_confirm.style.backgroundColor="white"; 
    } 
} 
</script> 
+0

問題在哪裏?請更具體的 –

+1

你的方法出了什麼問題?順便說一句,我強烈建議使用服務器端驗證,而不是或者除了您的JavaScript驗證。 – showdev

+0

對不起,問題是由於某種原因,表格仍然提交,即使我沒有輸入確認的密碼。我如何驗證這一點,以確保提交表單前密碼匹配? – munue

回答

2

你在哪裏打電話validatepw?

可以在兩個pwd字段添加onchange =「javascript:validatepw()」

+0

我會試試這個。 – munue

+0

嘿,這工作完美。我只是將onchange =「validpw()」添加到確認密碼字段中。非常感謝你的幫助 – munue