views:

84

answers:

4

Hi, i'm using jquery and I'm trying to validate a form. My question is - What is the maximum number of tests can you give in a single if statement.

function cc_validate () {
if ($("#name").val() == "" || $("#ship_name").val() == "" || $("#address").val() == "" || $("#city").val() == "" || $("#ship_city").val() == "" || $("#state").val() == "" || $("#ship_state").val() == "" || $("#postal_code").val() == "" || isNaN($("#postal_code").val()) || $("#phone").val() == "" || $("#ship_phone").val() == "" || isNaN($("#phone").val()) || isNaN($("#ship_phone").val()) || $("#mobile_number").val() == "" || $("#ship_mobile_number").val() == "" || isNaN($("#mobile_number").val()) || isNaN($("#ship_mobile_number").val()) || $("#email").val() == "") {
return false;

}  else {

return true;
  } }
+5  A: 

You can do as many as you want, but if you're using too many tests then you're doing something wrong and the programmer that will have to re-use your code (possibily yourself) will hate you.

marcgg
... and I'd say that the code you pasted has waaaaaay too many <strike>if statements</strike> tests
marcgg
There's only 1 if statement in that code...
thenduks
I meant tests... my bad, I'm fixing this
marcgg
A: 

The number is limited only by code readability. In this case I'd say it's not (readable, that is) :).

Also, if you're asking why this code doesn't work then it as someone mentioned in a comment, $"#name" (and the rest) are invalid syntax. Since $ is a function you need to put it's argument in parentheses: $('#name')...

thenduks
+5  A: 

Why, insted of your unreadable if (and think about managing it later, also), not add some classes to your code, like this:

<input id="postal_code" class="required number" />

and have your jquery check it like this:

function cc_validate() {
  $(".required").each(function() {
    if (this.val() == '') return false;
  }
  $(".number").each(function() {
    if (isNaN(this.val()) return false;
  }
}

and such...?

kender
+2  A: 

If you don't want to use classes, just add all your field names to an array and iterate it.

Not only will increase readability, but also you don't have to worry any more with the number of operators.

It is a simpler solution, but not as nice has using classes as kender suggested.

Luís Duarte