Add the ability to create custom validation on fields
This commit is contained in:
parent
13bfb1c972
commit
fa9676779b
|
@ -10,6 +10,16 @@ Validatable.validatesNumericalityOf = getConfigurator('numericality');
|
||||||
Validatable.validatesInclusionOf = getConfigurator('inclusion');
|
Validatable.validatesInclusionOf = getConfigurator('inclusion');
|
||||||
Validatable.validatesExclusionOf = getConfigurator('exclusion');
|
Validatable.validatesExclusionOf = getConfigurator('exclusion');
|
||||||
Validatable.validatesFormatOf = getConfigurator('format');
|
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
|
// implementation of validators
|
||||||
var validators = {
|
var validators = {
|
||||||
|
@ -118,7 +128,8 @@ function validationFailed(inst, v) {
|
||||||
if (skipValidation(inst, conf, 'unless')) return false;
|
if (skipValidation(inst, conf, 'unless')) return false;
|
||||||
|
|
||||||
var fail = 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;
|
var message;
|
||||||
if (conf.message) {
|
if (conf.message) {
|
||||||
message = conf.message;
|
message = conf.message;
|
||||||
|
|
|
@ -215,3 +215,16 @@ it 'should validate format', (test) ->
|
||||||
|
|
||||||
test.done()
|
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()
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue