Handle custom error codes

Fixes #151
This commit is contained in:
Fabien Franzen 2014-07-11 23:03:07 +02:00
parent a58dbe3a54
commit 50656b8206
2 changed files with 6 additions and 4 deletions

View File

@ -506,7 +506,7 @@ function validationFailed(inst, v, cb) {
validatorArguments.push(attr);
validatorArguments.push(conf);
validatorArguments.push(function onerror(kind) {
var message, code = conf.validation;
var message, code = conf.code || conf.validation;
if (conf.message) {
message = conf.message;
}

View File

@ -295,21 +295,23 @@ describe('validations', function () {
it('should validate using custom sync validation', function() {
User.validate('email', function (err) {
if (this.email === 'hello') err();
});
}, { code: 'invalid-email' });
var u = new User({email: 'hello'});
Boolean(u.isValid()).should.be.false;
u.errors.codes.should.eql({ email: ['invalid-email'] });
});
it('should validate and return detailed error messages', function() {
User.validate('global', function (err) {
if (this.email === 'hello' || this.email === 'hey') {
this.errors.add('hello', 'Cannot be `' + this.email + '`', 'invalid');
this.errors.add('email', 'Cannot be `' + this.email + '`', 'invalid-email');
err(false); // false: prevent global error message
}
});
var u = new User({email: 'hello'});
Boolean(u.isValid()).should.be.false;
u.errors.should.eql({ hello: [ 'Cannot be `hello`' ] });
u.errors.should.eql({ email: ['Cannot be `hello`'] });
u.errors.codes.should.eql({ email: ['invalid-email'] });
});
it('should validate using custom async validation', function(done) {