How to Validate Form Data in Express.js

Updated: December 28, 2023 By: Guest Contributor Post a comment

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!