Sling Academy
Home/Node.js/How to Validate Form Data in Express.js

How to Validate Form Data in Express.js

Last updated: December 28, 2023

Overview

Form validation is an essential aspect of web development that ensures the data collected through web forms is clean, correctly formatted, and meets specific criteria before it is processed or stored. In Express.js, which is a minimal and flexible Node.js web application framework, form validation can be implemented in various ways ranging from manual validation to using middleware like express-validator.

This tutorial will cover several methods of validating form data in an Express.js application, starting with basic manual assertions up to utilizing robust libraries for advanced scenarios.

Before You Begin

Ensure you have a basic Express.js application set up. You need to have Node.js installed on your system and a basic understanding of JavaScript and Express.js.

Manual Validation

First, we’ll perform some simple manual validation on our form data:

const express = require('express');
const app = express();

app.use(express.urlencoded({ extended: true }));

app.post('/submit-form', (req, res) => {
    const { name, email } = req.body;

    if(!name) {
        return res.status(400).send('Name is required');
    }

    if(!email.includes('@')) {
        return res.status(400).send('Please enter a valid email');
    }

    // Process the data...
});

Using express-validator

express-validator is a powerful tool for form validation. It is built on top of validator.js, which provides a lot of validation and sanitization functions.

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

app.post('/submit-form',
    [
        body('name').notEmpty().withMessage('Name is required'),
        body('email').isEmail().withMessage('Please enter a valid email')
    ],
    (req, res) => {
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            return res.status(400).json({ errors: errors.array() });
        }

        // Process the data...
    }
);

The express-validator library provides several methods to define the validation chain. Here, we used body to validate ‘name’ can’t be empty and ’email’ should be a valid email format.

Advanced Validation Techniques

For more advanced scenarios, we can combine express-validator checks with custom validation functions:

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

app.post('/submit-form',
    [
        body('name').notEmpty().withMessage('Name is required'),
        body('email').isEmail().withMessage('Please enter a valid email'),
        body('password').isLength({ min: 6 }).withMessage('Password must be at least 6 characters'),
        body('confirmPassword').custom((value, { req }) => {
            if(value !== req.body.password) {
                throw new Error('Password confirmation does not match password');
            }
            return true;
        })
    ],
    (req, res) => {
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            return res.status(400).json({ errors: errors.array() });
        }

        // Process the data...
    }
);

Asynchronous Validation

In some cases, you might need to perform asynchronous operations during validation, such as database lookups:

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

app.post('/submit-form',
    [
        body('username').custom(async (username) => {
            const existingUser = await User.findOne({ username });
            if (existingUser) {
                throw new Error('Username is already taken');
            }
        })
    ],
    (req, res) => {
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            return res.status(400).json({ errors: errors.array() });
        }

        // Process the data...
    }
);

Here, we’ve used a custom validator that performs an asynchronous database lookup to check if the username already exists.

Conclusion

Form validation is a critical component of web applications, and Express.js offers multiple ways to achieve it. Beginners can perform manual validation, although it’s not optimal for complex scenarios. As applications grow, middleware like express-validator becomes more appropriate due to its simplicity and extensive set of validation rules. Always remember to validate data both on the client and server sides to ensure security and data integrity.

By integrating these validation techniques into your Express.js applications, you can catch errors before they become bigger issues, and provide a more robust user experience. Happy coding!

Next Article: How to Block IP Addresses in Express.js

Previous Article: How to Extract Request Body in Express JS

Series: Node.js & Express Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates