Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Add the ability to create custom validation on fields

  • Loading branch information...
commit fa9676779bcc467e29fda0b81a06dac871f104f4 1 parent 13bfb1c
@juggy juggy authored
Showing with 25 additions and 1 deletion.
  1. +12 −1 lib/validatable.js
  2. +13 −0 test/validations_test.coffee
View
13 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;
View
13 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()
+
Please sign in to comment.
Something went wrong with that request. Please try again.