Skip to content

Instantly share code, notes, and snippets.

@NoumanSaleem
Last active December 21, 2015 21:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NoumanSaleem/6366731 to your computer and use it in GitHub Desktop.
Save NoumanSaleem/6366731 to your computer and use it in GitHub Desktop.
Extend Node Validator to support per-check title + return total number of errors.
/*
Usage:
Var Validator = require('path-To-Your/lib/validator'),
validator = new Validator();
validator.checkField('first_name', 'foo', {
isNumeric: 'This is not a number',
contains: 'The value doesn\'t have a 0 in it'
}).isNumeric().contains('0');
validator.getErrors();
// returns:
{ fields:
{ first_name: [ 'This is not a number', 'The value doesn\'t have a 0 in it' ] }
total: 2 }
*/
var Validator = require('validator').Validator;
Validator.prototype.error = function (msg) {
if (this.fieldName) {
if (!this._errors.fields[this.fieldName]) this._errors.fields[this.fieldName] = [];
this._errors.fields[this.fieldName].push(msg);
this._errors.total++;
} else {
this._errors.push(msg);
}
return this;
};
Validator.prototype.getErrors = function () {
return this._errors;
};
Validator.prototype.checkField = function (fieldName, str, fail_msg) {
this._errors = this._errors || { fields: {}, total: 0 };
this.fieldName = fieldName;
return this.check(str, fail_msg);
};
module.exports = Validator;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment