From fa9676779bcc467e29fda0b81a06dac871f104f4 Mon Sep 17 00:00:00 2001 From: Julien Guimont Date: Wed, 16 Nov 2011 22:37:43 -0500 Subject: [PATCH] Add the ability to create custom validation on fields --- lib/validatable.js | 13 ++++++++++++- test/validations_test.coffee | 13 +++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/lib/validatable.js b/lib/validatable.js index f8d55405..bde3b4fb 100644 --- a/lib/validatable.js +++ b/lib/validatable.js @@ -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; diff --git a/test/validations_test.coffee b/test/validations_test.coffee index d3e2c3cf..14bd4ec0 100644 --- a/test/validations_test.coffee +++ b/test/validations_test.coffee @@ -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() +