How do you validate multiple items in JavaScript, but without nesting ifs?
Not this...
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
}
...rather, this...
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
}
});
Do you have开发者_运维技巧 any ideas? Thanks for reply!
You can use the jQuery Validation Plugin, which will be much easier and more effective than duplicating it yourself.
I usually handle things like this like so:
var error = new Array();
var errorNum = 0;
if(!(username && username.length > 2 && ...)) {
error[errorNum++] = "ERROR1";
}
if(!(password &&...)) {
error[errorNum++] = "ERROR2";
}
No nesting required.
Edit: Sorry, initial syntax as PhP not javascript. I mix the two too often sometimes.
精彩评论