Written by: Geoffrey Callaghan
Validator.js tutorial
Validator.Js Tutorial
Validator.js is a robust library for validating and sanitizing strings in JavaScript. It provides a wide array of functions to ensure the validity and cleanliness of input data. This tutorial will guide you through the basics of using Validator.js in a Node.js environment.
To get started, you need to install Validator.js using npm or yarn:
npm install validator
# or
yarn add validator
First, let’s explore some basic validation functions provided by Validator.js.
const validator = require('validator');
const email = 'test@example.com';
console.log(validator.isEmail(email)); // true
const url = 'https://www.example.com';
console.log(validator.isURL(url)); // true
const phoneNumber = '123-456-7890';
console.log(validator.isMobilePhone(phoneNumber, 'en-US')); // true
const alphaString = 'HelloWorld';
console.log(validator.isAlpha(alphaString)); // true
Validator.js also provides functions to sanitize input data.
let dirtyString = ' Hello World! ';
let cleanString = validator.trim(dirtyString);
console.log(cleanString); // 'Hello World!'
dirtyString = 'Hello <script>alert("Hacked!")</script> World!';
cleanString = validator.escape(dirtyString);
console.log(cleanString); // 'Hello <script>alert("Hacked!")</script> World!'
const dirtyEmail = 'Test@Example.Com';
const cleanEmail = validator.normalizeEmail(dirtyEmail);
console.log(cleanEmail); // 'test@example.com'
You can create custom validation functions using Validator.js.
function isStrongPassword(password) {
const minLength = 8;
const hasUpperCase = /[A-Z]/.test(password);
const hasLowerCase = /[a-z]/.test(password);
const hasNumber = /[0-9]/.test(password);
const hasSpecialChar = /[!@#$%^&*]/.test(password);
return password.length >= minLength && hasUpperCase && hasLowerCase && hasNumber && hasSpecialChar;
}
const password = 'Str0ngP@ssw0rd!';
console.log(isStrongPassword(password)); // true
Validator.js is commonly used in conjunction with Express to validate user input in web applications.
First, install Express:
npm install express
const express = require('express');
const validator = require('validator');
const app = express();
app.use(express.json());
app.post('/signup', (req, res) => {
const { email, password } = req.body;
if (!validator.isEmail(email)) {
return res.status(400).json({ error: 'Invalid email address' });
}
if (!isStrongPassword(password)) {
return res.status(400).json({ error: 'Password is not strong enough' });
}
res.status(200).json({ message: 'Validation succeeded' });
});
function isStrongPassword(password) {
const minLength = 8;
const hasUpperCase = /[A-Z]/.test(password);
const hasLowerCase = /[a-z]/.test(password);
const hasNumber = /[0-9]/.test(password);
const hasSpecialChar = /[!@#$%^&*]/.test(password);
return password.length >= minLength && hasUpperCase && hasLowerCase && hasNumber && hasSpecialChar;
}
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Validator.js includes many other useful functions for different types of validation and sanitization.
const ipAddress = '192.168.1.1';
console.log(validator.isIP(ipAddress)); // true
const ipv6Address = '2001:0db8:85a3:0000:0000:8a2e:0370:7334';
console.log(validator.isIP(ipv6Address, 6)); // true
const creditCardNumber = '4111111111111111';
console.log(validator.isCreditCard(creditCardNumber)); // true
const uuid = '550e8400-e29b-41d4-a716-446655440000';
console.log(validator.isUUID(uuid)); // true
Validator.js is a versatile library that simplifies the process of validating and sanitizing strings in JavaScript applications. This tutorial covered the basics, including setup, basic validation and sanitization functions, custom validation, and usage with Express. For more advanced usage and a comprehensive list of available functions, refer to the official Validator.js documentation.