Last active
December 21, 2015 21:09
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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