How To Validate Body in NodeJS with Express-Validator

5 min read
Express Validator

Express-Validator is a middleware module for Express.js. It simplifies the process of validating body of the request to ensure that data sent to your server meets the required criteria. This guide will walk you through the basics of using Express-Validator to handle and validate incoming data in your Express.js applications.

Installation

To get started, you need to install Express-Validator using npm. Open your terminal and run the following command:

npm install express-validator

This will add Express-Validator to your project’s dependencies.

Setting Up Express-Validator

In your Express.js application, you need to require and configure the Express-Validator middleware. Add the following lines to your code:

const express = require('express'); 
const { body, validationResult } = require('express-validator'); 
const app = express(); 
// Your other middleware and route handling code 
app.listen(3000, () => { console.log('Server is running on port 3000'); });

Basic Validation

Express-Validator provides a variety of validation methods for different types of input. Here are some basic examples:

String Validation

To validate a string input, you can use the body method with the isString validator:

app.post('/signup', [
    body('username').isString(),
    body('password').isString().isLength({ min: 6 }),
], (req, res) => {
    // Your route handling code
});

In this example, the username and password fields must be strings, and the password must have a minimum length of 6 characters.

Number Validation

For numeric input, you can use the isNumeric validator:

app.post('/order', [
    body('quantity').isNumeric(),
    body('price').isNumeric(),
], (req, res) => {
    // Your route handling code
});

This ensures that the quantity and price fields contain only numeric values.

Date Validation

To validate date input, you can use the isISO8601 validator:

app.post('/event', [
    body('date').isISO8601(),
], (req, res) => {
    // Your route handling code
});

This checks if the date field follows the ISO 8601 date format.

Custom Validators

Express-Validator allows you to create custom validation functions to suit your specific needs. Here’s an example of a custom email validation:

const isValidEmail = (value) => {
    // Your custom email validation logic
    return /\S+@\S+\.\S+/.test(value);
};

app.post('/contact', [
    body('email').custom((value) => {
        if (!isValidEmail(value)) {
            throw new Error('Invalid email address');
        }
        return true;
    }),
], (req, res) => {
    // Your route handling code
});

In this example, the custom validator is used to apply the isValidEmail function to the email field.

Validation Chains

You can chain multiple validators together for more complex validation scenarios. For example:

app.post('/update-profile', [
    body('username').isString().isLength({ min: 5 }),
    body('email').isEmail(),
    body('age').isNumeric().isInt({ min: 18, max: 99 }),
], (req, res) => {
    // Your route handling code
});

Here, the update-profile route expects a username with a minimum length of 5 characters, a valid email address, and a numeric age between 18 and 99.

Error Handling

To handle validation errors, you can use the validationResult function provided by Express-Validator. Update your route handling code as follows:

app.post('/signup', [
    body('username').isString(),
    body('password').isString().isLength({ min: 6 }),
], (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
        return res.status(400).json({ errors: errors.array() });
    }

    // Proceed with the route handling code
});

This checks for validation errors and returns a 400 Bad Request response with an array of errors if any are found.

Sanitization

Express-Validator not only validates data but also provides a set of sanitization methods to clean and sanitize input. For example, to remove leading and trailing spaces from a string:

app.post('/update-profile', [
    body('username').isString().trim(),
    body('email').isEmail().normalizeEmail(),
], (req, res) => {
    // Your route handling code with sanitized data
});

In this example, the trim method removes leading and trailing spaces from the username field, and normalizeEmail normalizes the email address.

10. Validation Result

The validationResult function returns an object that provides information about the validation process. You can access the array of errors, check if there are errors, and extract specific error messages:

app.post('/login', [
    body('username').isString(),
    body('password').isString().isLength({ min: 6 }),
], (req, res) => {
    const result = validationResult(req);

    if (!result.isEmpty()) {
        const errors = result.array();
        // Handle errors or log them
    }

    // Your route handling code
});

Handling Validation Errors

Express-Validator makes it easy to handle validation errors by providing detailed error messages. You can customize the error messages by using the withMessage method:


Copy code
app.post('/create-comment', [
    body('text').isString().isLength({ min: 10 }).withMessage('Comment must be at least 10 characters long'),
], (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
        return res.status(400).json({ errors: errors.array() });
    }

    // Your route handling code
});

In this example, the custom error message is attached to the text field validation.

Express Validator Methods

Here’s a list of some Express-Validator most used methods. These methods can be used to create robust validation rules for your Express routes. You can combine them and customize options as needed for your specific use cases

  1. check(field, [message]):
    • Basic validation method for checking a field.
  2. body(field, [message]):
    • Similar to check(), specifically used for the request body.
  3. param(field, [message]):
    • Used for validating route parameters.
  4. query(field, [message]):
    • Validates query parameters in the URL.
  5. custom(validatorFunction):
    • Allows you to define a custom validation function.
  6. contains(seed)
    • Checks if a field contains the specified substring or character.
  7. isEmail([options]):
    • Checks if a given field is a valid email address.
  8. isLength(options):
    • Validates the length of a string.
  9. isNumeric([options]):
    • Ensures that a field is a numeric value.
  10. isURL([options]):
    • Validates if a field is a valid URL.
  11. isInt([options]):
    • Checks if a field is an integer.
  12. isFloat([options]):
    • Validates if a field is a floating-point number.
  13. isAlphanumeric([locale]):
    • Ensures that a field contains only letters and numbers.
  14. isDate():
    • Checks if a field is a valid date.
  15. isBoolean():
    • Validates if a field is a boolean value.
  16. isIn(values):
    • Checks if a field’s value is within a specified array of values.
  17. isCurrency([options]):
    • Validates if a field is in a currency format.
  18. isAfter(date) / isBefore(date):
    • Ensures a date is after/before a specified date.
  19. isMobilePhone([locale, options]):
    • Validates if a field is a valid mobile phone number.
  20. isAlpha([locale]):
    • Ensures that a field contains only alphabetic characters.
  21. isAscii():
    • Validates if a field contains only ASCII characters.
  22. isHexColor():
    • Checks if a field is a valid hexadecimal color code.
  23. isMongoId():
    • Validates if a field is a valid MongoDB ObjectId.
  24. isPostalCode([locale]):
    • Ensures that a field is a valid postal code.
  25. isUppercase() / isLowercase():
    • Checks if a field is entirely in uppercase or lowercase.
  26. isBase64():
    • Validates if a field is a valid Base64-encoded string.
  27. isJSON():
    • Ensures that a field is a valid JSON string.
  28. isCreditCard():
    • Checks if a field is a valid credit card number.
  29. isISBN([version]):
    • Validates if a field is a valid ISBN (International Standard Book Number).

Conclusion

Express-Validator is a powerful middleware that simplifies the process of validating and sanitizing user input in your Express.js applications. By incorporating it into your projects, you can enhance the security and reliability of your web applications. As you become more familiar with Express-Validator, you can explore advanced features and tailor the validation process to meet the specific requirements of your applications.

Leave a Reply

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