Add the ability to create custom validation on fields

This commit is contained in:
Julien Guimont 2011-11-16 22:37:43 -05:00
parent 13bfb1c972
commit fa9676779b
2 changed files with 25 additions and 1 deletions

View File

@ -10,6 +10,16 @@ Validatable.validatesNumericalityOf = getConfigurator('numericality');
Validatable.validatesInclusionOf = getConfigurator('inclusion');
Validatable.validatesExclusionOf = getConfigurator('exclusion');
Validatable.validatesFormatOf = getConfigurator('format');
Validatable.validate = function(){
args = [].slice.call(arguments);
var valFn = function(){}; //noop
if (typeof args[args.length - 1] === 'function'){
valFn = args.pop();
}
wrapperFn = function(attr, conf, err){ return valFn.call( this, err) };
configure(this, wrapperFn, args)
}
// implementation of validators
var validators = {
@ -118,7 +128,8 @@ function validationFailed(inst, v) {
if (skipValidation(inst, conf, 'unless')) return false;
var fail = false;
validators[conf.validation].call(inst, attr, conf, function onerror(kind) {
var validator = typeof conf.validation === "function" ? conf.validation : validators[conf.validation];
validator.call(inst, attr, conf, function onerror(kind) {
var message;
if (conf.message) {
message = conf.message;

View File

@ -215,3 +215,16 @@ it 'should validate format', (test) ->
test.done()
it 'should validate a field using a custom validator', (test)->
User.validate 'email', (err)-> err("crash") if @email.length is 0
user = new User validAttributes
test.ok user.isValid()
user = new User validAttributes
user.email = ""
test.ok not user.isValid()
test.done()