2010-06-22 129 views
2

這裏是我的代碼:驗證檢查,如果密碼和確認密碼相同的工作不

function validate_form(thisform) 
{ 
with (thisform) 
    { 
     if (validate_required(name,"Name must be filled out!")==false) 
    {name.focus();return false;} 
    if (validate_required(country," Country must be filled out!")==false) 
    {country.focus();return false;} 
    if (validate_required(state,"State must be filled out!")==false) 
    {state.focus();return false;} 
    if (validate_required(city,"City must be filled out!")==false) 
    {city.focus();return false;} 
    if (validate_required(contact,"Contact must be filled out!")==false) 
    {contact.focus();return false;} 
    if (validate_required(emailid,"Email must be filled out!")==false) 
    {emailid.focus();return false;} 
    if (validate_email(userid,"Email is not valid")==false) 
    {userid.focus();return false;} 
    if (validate_required(password,"pasword must be filed out")==false) 
    {password.focus();return false;} 
    if (validate_required(cpassword,"Password must be confirmed")==false) 
    {cpassword.focus();return false;} 

if(validate_required((password.value != cpassword.value),"Your password and confirmation password do not match.")==false) { 
cpassword.focus();return false; 


} 

所有其他驗證正在努力,但不是最後一個。爲什麼是這樣以及如何解決它?

回答

6

我想你已經從這個頁面得到了validate_required()函數:http://www.w3schools.com/js/js_form_validation.asp

function validate_required(field,alerttxt) 
{ 
with (field) 
    { 
    if (value==null||value=="") 
    { 
    alert(alerttxt);return false; 
    } 
    else 
    { 
    return true; 
    } 
    } 
} 

在這種情況下,您的最後一個條件將不會像您期望的那樣工作。仍然

if (password.value != cpassword.value) { 
    alert("Your password and confirmation password do not match."); 
    cpassword.focus(); 
    return false; 
} 
+0

我替換了它,但它仍然不起作用 – 2010-06-22 12:54:27

+0

「if(password.value!= cpassword.value){」add this:alert(password.value!= cpassword.value);你到了那裏? – DmitryK 2010-06-22 13:07:01

+0

我沒有得到任何東西 – 2010-06-22 13:08:26

3

validate_required函數似乎期望HTML表單控件(例如文本輸入字段)作爲第一個參數,並檢查是否有值。這不是你想要的。

此外,當您寫['password'].value,創建長度爲1的新的數組,含有string'password',然後讀取不存在的從它屬性"value",得到未定義的值。

你可能想嘗試的卻是:

if (password.value != cpassword.value) { cpassword.focus(); return false; } 

(你還需要以某種方式編寫錯誤消息,但我無法從你的代碼如何做到這一點看)。

+0

它不工作 – 2010-06-22 12:48:12

+0

錯誤味精是作爲參數傳遞給函數 – 2010-06-22 12:49:35

+0

@bhavna raghuvanshi:

你可以用這個代替它是變量'password'和'cpassword'設置,以便它們包含DOM元素?例如,你的函數內部的alert(password.value)是什麼? – Boldewyn 2010-06-22 12:50:25

1
function validate() 
{ 
    var a=documents.forms["yourformname"]["yourpasswordfieldname"].value; 
    var b=documents.forms["yourformname"]["yourconfirmpasswordfieldname"].value; 
    if(!(a==b)) 
    { 
    alert("both passwords are not matching"); 
    return false; 
    } 
    return true; 
}