Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Merge pull request #1775 from tjbutz/master

Allow to define a type for custom SchemaType validators
  • Loading branch information...
commit c99ced055c367874bdd7c72d2a022ca98e1602b2 2 parents c4a0f28 + 3a0ec5f
@aheckmann aheckmann authored
Showing with 46 additions and 3 deletions.
  1. +5 −3 lib/schematype.js
  2. +41 −0 test/schema.validation.test.js
View
8 lib/schematype.js
@@ -392,14 +392,16 @@ SchemaType.prototype.get = function (fn) {
*
* @param {RegExp|Function|Object} obj validator
* @param {String} [errorMsg] optional error message
+ * @param {String} [type] optional validator type
* @return {SchemaType} this
* @api public
*/
-SchemaType.prototype.validate = function (obj, message) {
+SchemaType.prototype.validate = function (obj, message, type) {
if ('function' == typeof obj || obj && 'RegExp' === obj.constructor.name) {
if (!message) message = errorMessages.general.default;
- this.validators.push([obj, message, 'user defined']);
+ if (!type) type = 'user defined';
+ this.validators.push([obj, message, type]);
return this;
}
@@ -415,7 +417,7 @@ SchemaType.prototype.validate = function (obj, message) {
throw new Error(msg);
}
- this.validate(arg.validator, arg.msg);
+ this.validate(arg.validator, arg.msg, arg.type);
}
return this;
View
41 test/schema.validation.test.js
@@ -481,5 +481,46 @@ describe('schema', function(){
})
})
})
+
+ describe('types', function(){
+ describe('are customizable', function(){
+ it('for single custom validators', function(done){
+ function validate () {
+ return false;
+ }
+ var validator = [validate, '{PATH} failed validation ({VALUE})', 'customType'];
+
+ var schema = new Schema({ x: { type: [], validate: validator }});
+ var M = mongoose.model('custom-validator-'+random(), schema);
+
+ var m = new M({ x: [3,4,5,6] });
+
+ m.validate(function (err) {
+ assert.equal('x failed validation (3,4,5,6)', String(err.errors.x));
+ assert.equal('customType', err.errors.x.type);
+ done();
+ })
+ })
+
+ it('for many custom validators', function(done){
+ function validate () {
+ return false;
+ }
+ var validator = [
+ { validator: validate, msg: '{PATH} failed validation ({VALUE})', type: 'customType'}
+ ]
+ var schema = new Schema({ x: { type: [], validate: validator }});
+ var M = mongoose.model('custom-validator-'+random(), schema);
+
+ var m = new M({ x: [3,4,5,6] });
+
+ m.validate(function (err) {
+ assert.equal('x failed validation (3,4,5,6)', String(err.errors.x));
+ assert.equal('customType', err.errors.x.type);
+ done();
+ })
+ })
+ })
+ })
});
});
Please sign in to comment.
Something went wrong with that request. Please try again.