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.

Step 1: Setup Your Project

To get started, you need to install Validator.js using npm or yarn:

npm install validator
# or
yarn add validator

Step 2: Basic Usage

First, let’s explore some basic validation functions provided by Validator.js.

  1. Importing Validator.js:
const validator = require('validator');
  1. Using basic validation functions:
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

Step 3: Sanitization Functions

Validator.js also provides functions to sanitize input data.

  1. Sanitizing strings:
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 &lt;script&gt;alert(&quot;Hacked!&quot;)&lt;/script&gt; World!'
  1. Normalizing email addresses:
const dirtyEmail = 'Test@Example.Com';
const cleanEmail = validator.normalizeEmail(dirtyEmail);
console.log(cleanEmail); // 'test@example.com'

Step 4: Custom Validation Functions

You can create custom validation functions using Validator.js.

  1. Custom validation:
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

Step 5: Using Validator.js with Express

Validator.js is commonly used in conjunction with Express to validate user input in web applications.

  1. Set up an Express application:

First, install Express:

npm install express
  1. Create a basic Express server with validation:
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');
});

Step 6: Advanced Usage

Validator.js includes many other useful functions for different types of validation and sanitization.

  1. Validating IP addresses:
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
  1. Validating credit card numbers:
const creditCardNumber = '4111111111111111';
console.log(validator.isCreditCard(creditCardNumber)); // true
  1. Validating UUIDs:
const uuid = '550e8400-e29b-41d4-a716-446655440000';
console.log(validator.isUUID(uuid)); // true

Conclusion

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.