loliki
loliki

Reputation: 957

Jquery wrap multiple actions into one

I am building a form validation in jQuery. I have 3 fields and I have to validate them. I have this function

function validate(field){
  if(field.val().length === 0){
    field.removeClass().addClass("error");
        field.next().removeClass().addClass("error");
    } 
     else if (plz.val().length != 5) {
      field.removeClass().addClass("error");
      field.next().removeClass().addClass("error");
    }
     else {
     field.removeClass();
     field.next().removeClass();
    }

     return field;
    }

I have to check 2 more fields, email and phone number, is there a way I can somehow not repeat the code below to all the else if statements?

field.removeClass().addClass("error");
field.next().removeClass().addClass("error");

Upvotes: 1

Views: 41

Answers (1)

nicosantangelo
nicosantangelo

Reputation: 13716

Why not using a function to abstract the logic?

function handleErrorClass(field) {
  field.removeClass().addClass("error");
  field.next().removeClass().addClass("error");
}

And you use it like this:

handleErrorClass(field);

for each needed field

Upvotes: 1

Related Questions