Skip to content

Instantly share code, notes, and snippets.

@aroc
Created February 25, 2013 00:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aroc/5026430 to your computer and use it in GitHub Desktop.
Save aroc/5026430 to your computer and use it in GitHub Desktop.
Change to Backbone.Validations to allow for a "onlyWhen" property that runs a model function, and if it returns false the validator is skipped.
var getValidators = function(model, attr) {
var attrValidationSet = model.validation ? model.validation[attr] || {} : {};
// If the validator is a function or a string, wrap it in a function validator
if (_.isFunction(attrValidationSet) || _.isString(attrValidationSet)) {
attrValidationSet = {
fn: attrValidationSet
};
}
// Stick the validator object into an array
if(!_.isArray(attrValidationSet)) {
attrValidationSet = [attrValidationSet];
}
// Reduces the array of validators into a new array with objects
// with a validation method to call, the value to validate against
// and the specified error message, if any
return _.reduce(attrValidationSet, function(memo, attrValidation) {
// Don't run this validator if the onlyWhen function returns false.
if (attrValidation.hasOwnProperty('onlyWhen')) {
if (!model[attrValidation.onlyWhen]()) {
return;
} else {
delete attrValidation.onlyWhen;
}
}
_.each(_.without(_.keys(attrValidation), 'msg'), function(validator) {
memo.push({
fn: defaultValidators[validator],
val: attrValidation[validator],
msg: attrValidation.msg
});
});
return memo;
}, []);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment