2010-11-25 26 views
1

如何驗證JavaScript中的多個項目,但沒有嵌套ifs?你如何驗證多個項目?

不是這個...

if (username && username.length > 2 && username.length < 45) { 
    if (password && password.length ...) { 
    if (birthday && birthday.isNumeric ...) { 
     if (age && ... && ...) { 
     // Success 
     } else { 
     // Error 4 
     } 
    } else { 
     // Error 3  
    } 
    } else { 
    // Error 2 
    } 
} else { 
    // Error 1 
} 

......而這...

validate({ 

    validate 'username' and use these conditions 'username && username.length...', 
    validate 'password' and use these conditions 'password && password.length...', 
    validate 'birthday' and use these conditions 'birthday && birthday.isNumeric...', 
    validate 'age' and use these conditions 'age && ... && ...' 

}, function(error) { 

    if (!error) { 
    // Success 
    } 

}); 

你有什麼想法?感謝您的回覆!

+0

這些嵌套`if`語句,而不是對象。 – SLaks 2010-11-25 20:59:08

+0

@SLaks Fixed ... – 2010-11-25 21:05:08

回答

0

我通常處理這樣的事情,像這樣:

var error = new Array(); 
var errorNum = 0; 

if(!(username && username.length > 2 && ...)) { 
    error[errorNum++] = "ERROR1"; 
} 

if(!(password &&...)) { 
    error[errorNum++] = "ERROR2"; 
} 

無需嵌套。

編輯:對不起,初始語法爲PhP不是JavaScript。有時我經常混淆兩者。