Created
February 25, 2013 00:22
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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