Skip to content

Data validation and sanitization

chriso edited this page Dec 21, 2010 · 2 revisions

Node.io comes bundled with node-validator and provides two methods, assert() and filter(), for validating and sanitizing data.

Validation

Use the included this.assert(str) method to validate data. An exception will be thrown on invalid data.

run: function () {
    this.assert('[email protected]').len(6, 64).isEmail();       //Methods are chainable
    this.assert('abcdefghijklmnopzrtsuvqxyz').is(/^[a-z]+$/); 
    this.assert('abc').isInt();                               //Throws 'Invalid integer'
}

The full list of validation methods

is()                            //Alias for regex()
not()                           //Alias for notRegex()
isEmail()
isUrl()                         //Accepts http, https, ftp
isIP()
isAlpha()
isAlphanumeric()
isNumeric()                     
isInt()                         //isNumeric accepts zero padded numbers, e.g. '001', isInt doesn't
isLowercase()
isUppercase()
isDecimal()
isFloat()                       //Alias for isDecimal
notNull()
isNull()
notEmpty()                      //i.e. not just whitespace
equals(equals)
contains(str)
notContains(str)
regex(pattern, modifiers)       //Usage: regex(/[a-z]/i) or regex('[a-z]','i')
notRegex(pattern, modifiers)
len(min, max)                   //max is optional

Sanitization / filtering

Use the included this.filter(str) method to sanitize data.

run: function () {
    var str, num;
    str = this.filter('aaaaaaaaab').ltrim('a');        //'b'
    num = this.filter('123').toInt();
    str = this.filter('&lt;a&gt;').entityDecode();     //'<a>'
}

Full list of methods

trim(chars)                     //Trim optional `chars`, default is to trim whitespace (\r\n\t\s)
ltrim(chars)                    
rtrim(chars)                    
ifNull(replace)
toFloat()
toInt()
toBoolean()		                //True unless str = '0', 'false', or str.length == 0
toBooleanStrict()	            //False unless str = '1' or 'true'
entityDecode()                  //Decode HTML entities
entityEncode()
xss(is_image)                   //Remove common xss attack vectors
Clone this wiki locally