Validator function in Backbone I have inside a Backbone model validate function several if statements:

if(!attrs.firstAttr) errorMsg+="first attr mandatory";
if(!attrs.secondAttr) errorMsg+="second attr mandatory";


as you can see there is a lot of repetition (I have actually 10 fields to check with this. 

I was thinking of introducing an interface Validator with a method validate. Then implement a MandatoryFieldValidator with:

validate: function(attr, errors) {
   if(!attr) errors.push(attr + " mandatory");
}


So the validate method would become like this:

mandatoryFieldValidator.validate(attr.firstAttr, errors); // errors now is an array
mandatoryFieldValidator.validate(attr.secondAttr, errors);


Would you think is a good solution? I still don't like it because I need to rewrite it a lot of times. Next step would be to have some kind of foreach but I don't have a list of parameters. The attributes passed by the Backbone validate is an object with the properties of the model.

Would it be ok to declare an array with every element I want to validate like [attr.firstAttr, attr.secondAttr]? 

If yes, how would it be possible to do it in Backbone? I'm referring to the fact that _.each function from underscore.js just passes an array with a callback function and I still need to pass the error array and apply the validate method of my Validator.
I would approach that like this:

Have an array with all the fields you

var mandatoryFields = ['firstAttr','secondAttr'];


Then have a validate function that takes attrs, mandatoryFields and errors

function validate( o , mandatoryFields, errors )
{
  for( var i = 0 , i &lt; mandatoryFields.length ; i++ )
  {
    var field = mandatoryFields[i];
    if(!o[field]) 
      errors.push(field + " mandatory");
  }
}


Note that I replaced attrs with fields but fare more readable, I also added a new-line  after that if statement for readability.