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.