# 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.

• Have you tried to use Backbone.Validation plugin? It helps a lot! github.com/thedersen/backbone.validation – Juliano Alves Jul 19 '13 at 14:33
• @Juliano I know that plugin but my problem is that part of the validation needs to happen only when certain conditions are met. If I recall correctly, with Backbone.Validation you can't do that. – dierre Jul 19 '13 at 17:02
• I know this is an old post, but in general, providing us the real code with the 10 fields helps us finding a better answer ;) – konijn Apr 28 '14 at 13:28

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 < 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.