node-validator is a library of string validation, filtering and sanitization methods.
To install node-validator, use npm:
$ npm install validator
To use the library in the browser, include validator-min.js
Example
var check = require('validator').check,
sanitize = require('validator').sanitize
check('test@email.com').len(6, 64).isEmail();
check('abc').isInt();
check('abc', 'Please enter a number').isInt();
check('abcdefghijklmnopzrtsuvqxyz').is(/^[a-z]+$/);
var int = sanitize('0123').toInt();
var bool = sanitize('true').toBoolean();
var str = sanitize(' \s\t\r hello \n').trim();
var str = sanitize('aaaaaaaaab').ltrim('a');
var str = sanitize(large_input_str).xss();
var str = sanitize('<a>').entityDecode();
Web development
Often it's more desirable to check or automatically sanitize parameters by name (rather than the actual string). See this gist for instructions on binding the library to the request
prototype.
If you are using the express.js framework you can use the express-validator middleware to seamlessly integrate node-validator.
Example http://localhost:8080/?zip=12345&foo=1&textarea=large_string
get('/', function (req, res) {
req.onValidationError(function (msg) {
});
req.check('zip', 'Please enter a valid ZIP code').len(4,5).isInt();
req.check('email', 'Please enter a valid email').len(6,64).isEmail();
req.checkHeader('referer').contains('localhost');
req.sanitize('textarea').xss();
req.sanitize('foo').toBoolean();
});
List of validation methods
is()
not()
isEmail()
isUrl()
isIP()
isAlpha()
isAlphanumeric()
isNumeric()
isInt()
isLowercase()
isUppercase()
isDecimal()
isFloat()
notNull()
isNull()
notEmpty()
equals(equals)
contains(str)
notContains(str)
regex(pattern, modifiers)
notRegex(pattern, modifiers)
len(min, max)
isUUID(version)
isDate()
isAfter(date)
isBefore(date)
isIn(options)
notIn(options)
max(val)
min(val)
isArray()
isCreditCard()
List of sanitization / filter methods
trim(chars)
ltrim(chars)
rtrim(chars)
ifNull(replace)
toFloat()
toInt()
toBoolean()
toBooleanStrict()
entityDecode()
entityEncode()
xss()
xss(true)
Extending the library
When adding to the Validator prototype, use this.str
to access the string and this.error(this.msg || default_msg)
when the string is invalid
var Validator = require('validator').Validator;
Validator.prototype.contains = function(str) {
if (!~this.str.indexOf(str)) {
this.error(this.msg || this.str + ' does not contain ' + str);
}
return this;
}
When adding to the Filter (sanitize) prototype, use this.str
to access the string and this.modify(new_str)
to update it
var Filter = require('filter').Filter;
Filter.prototype.removeNumbers = function() {
this.modify(this.str.replace(/[0-9]+/g, ''));
return this.str;
}
Error handling
By default, the validation methods throw an exception when a check fails
try {
check('abc').notNull().isInt()
} catch (e) {
console.log(e.message);
}
To set a custom error message, set the second param of check()
try {
check('abc', 'Please enter a valid integer').notNull().isInt()
} catch (e) {
console.log(e.message);
}
To attach a custom error handler, set the error
method of the validator instance
var Validator = require('validator').Validator;
var v = new Validator();
v.error = function(msg) {
console.log('Fail');
}
v.check('abc').isInt();
You might want to collect errors instead of throwing each time
Validator.prototype.error = function (msg) {
this._errors.push(msg);
}
Validator.prototype.getErrors = function () {
return this._errors;
}
Contributors
- PING - Fixed entity encoding
- Dan VerWeire - Modified the behaviour of the error handler
- ctavan - Added isArray and isUUID()
- foxbunny - Added min(), max(), isAfter(), isBefore(), and improved isDate()
- oris - Addded in()
LICENSE
(MIT License)
Copyright (c) 2010 Chris O'Hara cohara87@gmail.com
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.