Search code examples
javascriptnode.jsexpress-validator

Validate data using express-validator in NodeJS?


I have created a validate that for validate every data before create, but i am not sure that my validator works. So, i would like to ask for help about this and i hope community can help me to improve my validator. I would like to receive your feedback and suggestions, if there's something wrong please tell me

// car.validator.js 
import { body } from "express-validator";

export var validateCar = () => {
  var regex = /^[A-Za-z0-9 ]+$/;
  var valid = regex.test(req.body.name);
  if (!req.body.name && !valid) {
    res.status(400).send({
      message: "Name can not be empty or not contains special characters",
    });
    return;
  } else if (!req.body.color) {
    res.status(400).send({
      message: "Color can not be empty!",
    });
    return;
  } else if (!req.body.brand) {
    res.status(400).send({
      message: "Brand can not be empty!",
    });
    return;
  }
};

Solution

  • Simplest way to use express-validator with node js is:

    Suppose I assume you are using /cars/create endpoint to send POST request which creates entry of car in your db then in your route file should be:

    const { check } = require("express-validator");
    router.post(
      "/cars/create",
      [
        check('name')
            .escape()
            .notEmpty()
            .matches(/^[A-Za-z0-9 ]+$/),
        check("color").notEmpty(),
        check("brand").notEmpty(),
      ],
      carsController.createCar
    );
    

    In your carsController.createCar you will have array of errors if validation is failed:

    const { validationResult } = require("express-validator");
    const createCar = async (req, res) => {
      const errors = validationResult(req);
        if (!errors.isEmpty()){
          return res
            .status(200)
            .json({ err: "Invalid Data Passed!", errors: errors });
        }
    
        // code to be implemented if validation is passed
    }
    

    check this doc for more details and your requirements.