Skip to content

Commit

Permalink
1.1.0 update to support additional property, and message/argument int…
Browse files Browse the repository at this point in the history
…erpolation. Dependencies were also updated, additional tests added, and default errors updated.
  • Loading branch information
Lee Powell committed Jun 9, 2015
1 parent 0435d6b commit 66a13e7
Show file tree
Hide file tree
Showing 5 changed files with 79 additions and 39 deletions.
43 changes: 30 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ var nameValidator = [
validate({
validator: 'isLength',
arguments: [3, 50],
message: 'Name should be between 3 and 50 characters'
message: 'Name should be between {args.0} and {args.1} characters' // Argument interpolation
}),
validate({
validator: 'isAlphanumeric',
Expand Down Expand Up @@ -64,21 +64,15 @@ Arguments to be passed to the validator. These can either be an array of argumen
Some of the validator.js validators require a value to check against (isEmail, isUrl etc). There may be instances where you don't have a value to check i.e. a path that is not required and as such these few validators return an false value causing validation to fail. This can now be bypassed by setting the `passIfEmpty` option.

### option.message - optional
Set the error message to be used should the validator fail. If no error message is set then mongoose-validator will attempt to use one of the built-in default messages, if it can't then a simple message of 'Error' will be returned.

### Extending the error properties (mongoose version >= 3.9.7)

Any additional members added to the options object will be available in the 'err.properties' field of the mongoose validation error.
Set the error message to be used should the validator fail. If no error message is set then mongoose-validator will attempt to use one of the built-in default messages, if it can't then a simple message of 'Error' will be returned. You can pass `{args.[argument index position]}` for crude argument interpolation. Note: Use `{args.0}` if your arguments isn't an array.

```javascript
var alphaValidator = validate({
validator: 'isAlphanumeric',
passIfEmpty: true,
message: 'Name should contain alpha-numeric characters only',
httpStatus: 400
});
validate({
validator: 'isLength',
arguments: [3, 50],
message: 'Name should be between {args.0} and {args.1} characters'
}),
```
In this example the error object returned by mongoose will have its 'properties' extended with httpStatus should validation fail.

## Regular Expressions

Expand Down Expand Up @@ -139,3 +133,26 @@ NOTE: As per validator.js documentation, the currently tested value is accessed
## Contributors

Special thanks to [Francesco Pasqua](https://github.com/cesconix/) for heavily refactoring the code into something far more future proof. Thanks also go to [Igor Escobar](https://github.com/igorescobar/) and [Todd Bluhm](https://github.com/toddbluhm/) for their contributions.

## License (MIT)

Copyright (c) 2015 Lee Powell <[email protected]>

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
7 changes: 6 additions & 1 deletion lib/default-errors.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,5 +33,10 @@ module.exports = {
isFullWidth: 'Does not contains full-width chars',
isHalfWidth: 'Does not contains half-width chars',
isVariableWidth: 'Does not contains a mixture of full and half-width chars',
isSurrogatePair: 'Does not contains any surrogate pairs chars'
isSurrogatePair: 'Does not contains any surrogate pairs chars',
isBoolean: 'Invalid boolean',
isCurrency: 'Invalid currency',
isISIN: 'Invalid ISIN',
isMobilePhone: 'Invalid mobile phone number',
isMongoId: 'Invalid MongoDB ID'
}
38 changes: 18 additions & 20 deletions lib/mongoose-validator.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,10 @@

var validatorjs = require('validator');
var defaultErrorMessages = require('./default-errors');
var _ = require('underscore');

var errorMessages = {};

validatorjs.extendCustom = function (name, fn) {
validatorjs[name] = function () {
var args = Array.prototype.slice.call(arguments);
return fn.apply(validatorjs, args);
};
};
module.exports = validate;

/**
* Create a validator object
Expand All @@ -30,20 +24,24 @@ validatorjs.extendCustom = function (name, fn) {
* @returns {object} Returns validator compatible with mongoosejs
* @throws Will throw error if validator does not exist
* @example
* require('mongoose-validator').validate({ validator: 'isLength', arguments: [4, 40], passIfEmpty: true, message: 'Value should be between 4 and 40 characters' );
* require('mongoose-validator').validate({ validator: 'isLength', arguments: [4, 40], passIfEmpty: true, message: 'Value should be between 4 and 40 characters', type: 'myType' );
*/
var validate = function(options) {
function validate (options) {
var name = options.validator;
var args = options.arguments || [];
var passIfEmpty = options.passIfEmpty !== undefined ? options.passIfEmpty : false;
var message = options.message || errorMessages[name] || defaultErrorMessages[name] || 'Error';
var type = options.type;
var validator = (name instanceof Function) ? name : validatorjs[name];
var extend = _.omit(options, 'passIfEmpty', 'message', 'validator', 'arguments');

// Coerse args into an array
args = !Array.isArray(args) ? [args] : args;

// Interpolate message with argument values
message = message.replace(/{args\.(\d+)}/g, function(replace, argIndex) {return args[argIndex]});

if (validator) {
return _.extend({
return {
validator: function(val, next) {
var validatorArgs = [val].concat(args);

Expand All @@ -53,8 +51,9 @@ var validate = function(options) {

return next(validator.apply(null, validatorArgs));
},
msg: message
}, extend);
message: message,
type: type
};
}

throw new Error('Validator `' + name + '` does not exist on validator.js');
Expand All @@ -70,17 +69,16 @@ var validate = function(options) {
* @example
* require('mongoose-validator').extend('isString', function (str) { return typeof str === 'string'; });
*/
var extend = function (name, fn, errorMsg) {
if (validatorjs[name] === undefined) {
validate.extend = function (name, fn, errorMsg) {
if (!validatorjs[name]) {
validatorjs[name] = function () { return fn.apply(validatorjs, Array.prototype.slice.call(arguments)); };
errorMessages[name] = errorMsg || 'Error';
validatorjs.extendCustom(name, fn);
}
else {
throw new Error('Validator `' + name + '` already exists on validator.js');
}
};

module.exports = validate;
module.exports.extend = extend;
module.exports.defaultErrorMessages = defaultErrorMessages;
module.exports.validatorjs = validatorjs;
validate.defaultErrorMessages = defaultErrorMessages;

validate.validatorjs = validatorjs;
13 changes: 8 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "mongoose-validator",
"description": "Validators for mongoose models utilising validator.js",
"version": "1.0.3",
"version": "1.1.0",
"author": {
"name": "Lee Powell",
"email": "[email protected]"
Expand All @@ -26,16 +26,19 @@
{
"name": "Kristijan Sedlak",
"url": "https://github.com/xpepermint"
},
{
"name": "Eric Saboia",
"url": "https://github.com/ericsaboia"
}
],
"dependencies": {
"underscore": "^1.8.2",
"validator": "^3.18.0"
},
"devDependencies": {
"mongoose": "3.8.x",
"mocha": "1.20.x",
"should": "3.3.x"
"mongoose": "^4.0.5",
"mocha": "^2.2.5",
"should": "^3.3.1"
},
"keywords": [
"mongoose",
Expand Down
17 changes: 17 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,23 @@ describe('Mongoose Validator', function() {
});
});

it('Should replace args on custom error message', function (done) {
schema.path('name').validate(validate({ validator: 'isLength', arguments: [5, 10], message: 'At least {args.0} and less than {args.1}' }));

should.exist(doc);

doc.name = 'Joe';

doc.save(function(err, person) {
should.exist(err);
should.not.exist(person);
err.should.be.instanceof(Error).and.have.property('name', 'ValidationError');
err.errors.name.should.have.property('path', 'name');
err.errors.name.message.should.equal('At least 5 and less than 10');
return done();
});
});

it('Should use a custom extend test and pass', function(done) {
schema.path('name').validate(validate({ validator: 'isType', arguments: 'string'}));

Expand Down

0 comments on commit 66a13e7

Please sign in to comment.