String validation and sanitization
The validator package is a production-grade library providing over 100 functions for string validation and sanitization in JavaScript and Node.js environments. With 17.5 million weekly downloads, it has become the de facto standard for verifying user input formats—from email addresses and URLs to credit card numbers, ISBNs, and IP addresses.
Unlike schema-based validation libraries, validator focuses exclusively on string primitives through a functional API. Each validator is a pure function that returns a boolean (for checks) or a transformed string (for sanitizers). This design makes it framework-agnostic and easily composable, whether you're building Express APIs, validating form data in React, or processing CSV imports in batch jobs.
The library emerged from the need for reliable, battle-tested validators that handle edge cases in real-world data. It powers popular frameworks like express-validator and is maintained with regular security patches—critical given its role in preventing injection attacks and data corruption. Every function accepts an options object for customization, allowing you to enforce specific formats (like requiring HTTPS in URLs or setting minimum password complexity).
const validator = require('validator');
// Registration endpoint validation example
function validateUserRegistration(req) {
const errors = [];
const { email, password, website, age } = req.body;
// Email validation with normalization
if (!validator.isEmail(email)) {
errors.push({ field: 'email', message: 'Invalid email format' });
}
const normalizedEmail = validator.normalizeEmail(email, {
gmail_remove_dots: true,
all_lowercase: true
});
// Strong password with custom requirements
const passwordStrength = validator.isStrongPassword(password, {
minLength: 10,
minLowercase: 1,
minUppercase: 1,
minNumbers: 1,
minSymbols: 1,
returnScore: true
});
if (passwordStrength < 30) {
errors.push({ field: 'password', message: 'Password too weak' });
}
// Optional URL validation with strict protocol
if (website && !validator.isURL(website, {
protocols: ['https'],
require_protocol: true,
require_valid_protocol: true
})) {
errors.push({ field: 'website', message: 'Website must use HTTPS' });
}
// Sanitize and validate integer age
const sanitizedAge = validator.trim(age);
if (!validator.isInt(sanitizedAge, { min: 18, max: 120 })) {
errors.push({ field: 'age', message: 'Age must be between 18 and 120' });
}
return {
valid: errors.length === 0,
errors,
sanitized: { email: normalizedEmail, age: validator.toInt(sanitizedAge) }
};
}
// Usage in Express route
app.post('/register', (req, res) => {
const validation = validateUserRegistration(req);
if (!validation.valid) {
return res.status(400).json({ errors: validation.errors });
}
// Proceed with sanitized data
createUser(validation.sanitized);
res.status(201).json({ message: 'User created' });
});API request validation: Verify incoming POST/PUT data in Express or Fastify routes before database operations. Check that email fields contain valid addresses, phone numbers match E.164 format, and UUIDs conform to RFC4122 standards to prevent malformed data from corrupting your persistence layer.
Form input sanitization: Clean user-generated content before rendering or storage. Use escape() to neutralize HTML/JavaScript in text fields, trim() to remove accidental whitespace, and normalizeEmail() to standardize addresses (removing dots in Gmail, lowercasing domains) for duplicate detection.
Password strength enforcement: Implement registration flows with isStrongPassword() to require minimum lengths, mixed case, numbers, and symbols. The function returns granular scoring, letting you show real-time feedback as users type rather than binary pass/fail messages.
Data pipeline validation: Process CSV uploads or third-party API responses by validating ISBNs for book catalogs, IBANs for payment systems, or MAC addresses for network device inventories. The library's locale-aware validators (like isMobilePhone() supporting 150+ countries) handle international data correctly.
Security filters: Prevent open redirect vulnerabilities by validating redirect URLs with isURL({ require_protocol: true, host_whitelist: ['yourdomain.com'] }), or block malicious file uploads by checking MIME types with isMIMEType() before passing to storage services.
Express middleware for the validator module.
Object schema validation
Dead simple Object schema validation
TypeScript-first schema declaration and validation library with static type inference
npm install validatorpnpm add validatorbun add validator