Comprehensive Guide to Express Validator APIs for Robust Node.js Input Validation

Introduction to Express Validator

Express-validator is a set of Express.js middleware that wraps around validator.js, providing a range of powerful features for validating and sanitizing user inputs. It ensures robust input handling, improves app security, and enhances user experience.

Below, we delve into some of the key APIs that express-validator offers with useful code snippets and an example application.

API Examples

1. Check Function

 app.post('/user', [
   check('username').isAlphanumeric().withMessage('Username must be alphanumeric'),
   check('email').isEmail().withMessage('Email must be valid'),
 ], (req, res) => {
   // Handle validation results
 });

2. OneOf Function

 app.post('/check-user', oneOf([
   check('email').isEmail(),
   check('phone').isMobilePhone('en-US')
 ]), (req, res) => {
   // Handle validation results
 });

3. Body Function

 app.post('/profile', [
   body('age').isInt({ min: 0 }).withMessage('Age must be a positive integer'),
   body('website').optional().isURL().withMessage('Website must be a valid URL')
 ], (req, res) => {
   // Handle validation results
 });

4. Validation Result Function

 app.post('/login', [
   body('password').isLength({ min: 5 }).withMessage('Password must be at least 5 chars long'),
 ], (req, res) => {
   const errors = validationResult(req);
   if (!errors.isEmpty()) {
     return res.status(400).json({ errors: errors.array() });
   }

   // Process further if no validation errors
 });

5. Custom Validator

 app.post('/signup', [
   check('username').custom(value => {
     if (value.includes('admin')) {
       throw new Error('Username should not contain "admin"');
     }
     return true;
   })
 ], (req, res) => {
   // Handle validation results
 });

Example Application

 const express = require('express');
 const { check, oneOf, body, validationResult } = require('express-validator');

 const app = express();
 app.use(express.json());

 app.post('/register', [
   check('email').isEmail().withMessage('Enter a valid email'),
   body('password').isLength({ min: 5 }).withMessage('Password must be at least 5 chars long'),
   oneOf([
     check('phone').isMobilePhone(),
     check('telegram').isAlphanumeric().withMessage('Enter a valid Telegram username'),
   ])
 ], (req, res) => {
   const errors = validationResult(req);

   if (!errors.isEmpty()) {
     return res.status(422).json({ errors: errors.array() });
   }

   res.send('Registration successful');
 });

 const PORT = process.env.PORT || 3000;
 app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

With these fundamental APIs, express-validator helps in setting up robust validation mechanisms quite easily. This example demonstrates creating a registration endpoint that validates emails, passwords, and optionally phone numbers or telegram usernames.

Hash: 09ed64c30a966996b8aeda3e162494c27bf5cea28e26ea9c9fb4283678d6212a

Leave a Reply

Your email address will not be published. Required fields are marked *