Merge pull request #1508 from bmatson/master

Pass context to custom validators
This commit is contained in:
Miroslav Bajtoš 2018-03-22 16:17:38 +01:00 committed by GitHub
commit f0c092da21
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
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 = {};
}
conf.customValidator.call(this, err, done);
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();
});
});