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 = check sanitize = sanitize //Validate; //Methods are chainable; //Throws 'Invalid integer'; //Throws 'Please enter a number'; //Set a message per validator; //Referencing validator args from the message; //Sanitize / Filtervar int = ; //123var bool = ; //truevar str = ; //'hello'var str = ; //'b'var str = ;var str = ; //'<a>'
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
;
List of validation methods
//Alias for regex() //Alias for notRegex() //Accepts http, https, ftp //Combines isIPv4 and isIPv6 //Accepts valid hexcolors with or without # prefix //isNumeric accepts zero padded numbers, e.g. '001', isInt doesn't //Alias for isDecimal //i.e. not just whitespace //Usage: regex(/[a-z]/i) or regex('[a-z]','i') //max is optional //Version can be 3, 4 or 5 or empty, see http://en.wikipedia.org/wiki/Universally_unique_identifier //Alias for isUUID(3) //Alias for isUUID(4) //Alias for isUUID(5) //Uses Date.parse() - regex is probably a better choice //Argument is optional and defaults to today. Comparison is non-inclusive //Argument is optional and defaults to today. Comparison is non-inclusive //Accepts an array or string //Will work against Visa, MasterCard, American Express, Discover, Diners Club, and JCB card numbering formats
List of sanitization / filter methods
//Trim optional `chars`, default is to trim whitespace (\r\n\t ) //True unless str = '0', 'false', or str.length == 0 //False unless str = '1' or 'true' //Decode HTML entities //Escape &, <, >, and " //Remove common XSS attack vectors from user-supplied HTML //Remove common XSS attack vectors from images
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 = Validator;Validatorprototype { if !~thisstr this; return this; //Allow method chaining}
When adding to the Filter (sanitize) prototype, use this.str
to access the string and this.modify(new_str)
to update it
var Filter = Filter;Filterprototype { this; return thisstr;}
Error handling
By default, the validation methods throw an exception when a check fails
try catch e console; //Invalid integer
To set a custom error message, set the second param of check()
try catch e console; //Please enter a valid integer
To attach a custom error handler, set the error
method of the validator instance
var Validator = Validator;var v = ;v { console;}v; //'Fail'
You might want to collect errors instead of throwing each time
Validatorprototype { this_errors; return this;} Validatorprototype { return this_errors;} var validator = ; validator;validator; var errors = validator; // ['Invalid email', 'String is too small']
Contributors
- zero21xxx - Added per check messages
- 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 - Added in()
- mren - Decoupled rules
- Thorsten Basse - Cleanup and refinement of existing validators
- Neal Poole - Port the latest xss() updates from CodeIgniter
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.