Pass options argument to custom validators

This commit is contained in:
bmatson 2017-10-11 15:53:13 -04:00 committed by Miroslav Bajtoš
parent a5faee46bd
commit c3e502032e
No known key found for this signature in database
GPG Key ID: 6F2304BA9361C7E3
2 changed files with 59 additions and 4 deletions

View File

@ -379,7 +379,18 @@ function validateCustom(attr, conf, err, options, done) {
done = options;
options = {};
}
if (!done) {
// called from a sync validator, stick options on end
conf.customValidator.call(this, err, options);
} else {
if (conf.customValidator.length === 3) {
// if they declared the validator with 3 args, they are expecting options
conf.customValidator.call(this, err, options, done);
} else {
// otherwise just pass the expected two (no context)
conf.customValidator.call(this, err, done);
}
}
}
function escapeStringRegexp(str) {
@ -543,7 +554,7 @@ Validatable.prototype.isValid = function(callback, data, options) {
validationFailed(inst, attr, v, options, done);
});
} else {
if (validationFailed(inst, attr, v)) {
if (validationFailed(inst, attr, v, options)) {
valid = false;
}
}

View File

@ -314,8 +314,52 @@ describe('validations', function() {
should.exist(e);
e.should.be.instanceOf(Error);
e.should.be.instanceOf(ValidationError);
d.updateAttribute('name', 'Vasiliy', {options: 'options'}, function(e) {
should.not.exist(e);
d.updateAttribute('name', 'Vasiliy', {options: 'options'}, err => {
if (err) return done(err);
// test passed
done();
});
});
});
});
it('passes options to custom sync validator', done => {
delete User.validations;
User.validate('name', function(err, options) {
if (options.testFlag !== 'someValue') err();
});
User.create({name: 'Valid'}, {testFlag: 'someValue'}, function(e, d) {
d.updateAttribute('name', null, {testFlag: 'otherValue'}, function(e) {
should.exist(e);
e.should.be.instanceOf(ValidationError);
d.updateAttribute('name', 'Vasiliy', {testFlag: 'someValue'}, err => {
if (err) return done(err);
// test passed
done();
});
});
});
});
it('passes options to async validator', done => {
delete User.validations;
User.validateAsync('name', function(err, options, done) {
if (options.testFlag !== 'someValue') {
console.error(
'Unexpected validation options: %j Expected %j',
options, {testFlag: 'someValue'});
err();
}
process.nextTick(function() { done(); });
});
User.create({name: 'Valid'}, {testFlag: 'someValue'}, function(e, d) {
if (e) return done(e);
d.updateAttribute('name', null, {testFlag: 'otherValue'}, function(e) {
should.exist(e);
e.should.be.instanceOf(ValidationError);
d.updateAttribute('name', 'Vasiliy', {testFlag: 'someValue'}, err => {
if (err) return done(err);
// test passed
done();
});
});