Security News
Cloudflare Adds Security.txt Setup Wizard
Cloudflare has launched a setup wizard allowing users to easily create and manage a security.txt file for vulnerability disclosure on their websites.
validator
Advanced tools
The validator npm package is a library of string validators and sanitizers. It provides a variety of functions to validate and sanitize strings, such as checking if a string is in a certain format (e.g., email, URL) or transforming strings to ensure they are safe for use in different contexts.
Email Validation
Checks if the input string is an email.
const validator = require('validator');
console.log(validator.isEmail('test@example.com')); // true
URL Validation
Checks if the input string is a URL.
const validator = require('validator');
console.log(validator.isURL('https://www.example.com')); // true
Sanitizing Strings
Escapes HTML characters in the input string to prevent XSS attacks.
const validator = require('validator');
console.log(validator.escape('<script>alert("xss")</script>')); // '<script>alert("xss")</script>'
Checking String Length
Checks if the input string's length falls within a specified range.
const validator = require('validator');
console.log(validator.isLength('Hello', {min: 2, max: 10})); // true
Blacklisting Characters
Removes specified characters from the input string.
const validator = require('validator');
console.log(validator.blacklist('abc123', '123')); // 'abc'
Joi is a powerful schema description language and data validator for JavaScript. It allows for a more detailed and structured validation process compared to validator, including the ability to create custom validation schemas.
Yup is a JavaScript schema builder for value parsing and validation. It uses a schema-based approach similar to Joi and can be integrated with form libraries like Formik. It is more focused on object schema validation.
Class-validator works with classes and decorators to validate that the properties of an object conform to specified rules. It is typically used with TypeScript and integrates well with class-based frameworks like TypeORM.
Express-validator is a set of express.js middlewares that wraps validator.js functions. It is specifically designed for use with the Express web application framework and allows for easy integration of validation into the request processing pipeline.
A library of string validation, filtering and sanitization methods.
To install node-validator, use npm:
$ npm install validator
var check = require('validator').check;
var convert = sanitize = require('validator').sanitize
//Validate
check('test@email.com').len(6, 64).isEmail(); //Methods are chainable
check('abc').isInt(); //Throws 'Invalid integer'
check('abcdefghijklmnopzrtsuvqxyz').is(/^[a-z]+$/);
//Sanitize / Filter
var int = convert('0123').toInt(); //123
var bool = convert('true').toBoolean(); //true
var str = sanitize(' \s\t\r hello \n').trim(); //'hello'
var str = sanitize('aaaaaaaaab').ltrim('a'); //'b'
var str = sanitize(large_input_str).xss();
var str = sanitize('<a>').entityDecode(); //'<a>'
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
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
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; //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 = require('filter').Filter;
Filter.prototype.removeNumbers = function() {
this.modify(this.str.replace(/[0-9]+/g, ''));
return this.str;
}
By default, the validation methods throw an exception when a check fails
try {
check('abc').notNull().isInt()
} catch (e) {
console.log(e); //Invalid integer
}
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); //Please enter a valid integer
}
To attach a custom error handler, modify the error
method of the Validator class
var Validator = require('validator').Validator;
var v = new Validator();
v.error = function(msg) {
console.log('Fail');
}
v.check('abc').isInt(); //'Fail'
10.1.0
isISO31661Alpha3()
validator
(#809)FAQs
String validation and sanitization
The npm package validator receives a total of 9,798,631 weekly downloads. As such, validator popularity was classified as popular.
We found that validator demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Cloudflare has launched a setup wizard allowing users to easily create and manage a security.txt file for vulnerability disclosure on their websites.
Security News
The Socket Research team breaks down a malicious npm package targeting the legitimate DOMPurify library. It uses obfuscated code to hide that it is exfiltrating browser and crypto wallet data.
Security News
ENISA’s 2024 report highlights the EU’s top cybersecurity threats, including rising DDoS attacks, ransomware, supply chain vulnerabilities, and weaponized AI.