niko craft
niko craft

Reputation: 2987

validating with expressjs inside (res, req) function instead of inside a middleware

I'm using express-validator library to validate on the backend. This is the library:

https://express-validator.github.io/docs/index.html

I have this code

// ...rest of the initial code omitted for simplicity.
const { check, validationResult } = require('express-validator');

app.post('/user', [
  check('username').isEmail(),
  check('password').isLength({ min: 5 })
], (req, res) => {
  // Finds the validation errors in this request and wraps them in an object with handy functions
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(422).json({ errors: errors.array() });
  }

  User.create({
    username: req.body.username,
    password: req.body.password
  }).then(user => res.json(user));
});

Is it possible to call validation function inside the (req, res) =>{ }

I have some requirements where I need to check what has arrived in via request before I can construct the validation array.

Basically I would like to be able to do this:

app.post('/user', (req, res) => {

  const { importantParam, email, password, firstname, lastname } = request.body
  let validateThis = []

  if(importantParam == true)
     validateThis = [
        check('username').isEmail(),
        check('password').isLength({ min: 5 })
     ]
  else 
     validateThis = [
        check('username').isEmail(),
        check('password').isLength({ min: 5 })
        check('firstname').isLength({ min: 5 })
        check('lastname').isLength({ min: 5 })
     ]

  runValidationFunction(validateThis)

  //now below code can check for validation errors
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(422).json({ errors: errors.array() });
  }

  User.create({
    username: req.body.username,
    password: req.body.password
  }).then(user => res.json(user));
});

This is what I need to do, construct the validation array based on if one of the params has a specific value. I can't figure out how to do that with the first example since it seems request is not possible to access when taking this approach

app.post('/user', validationArray, (req, res) => {}

Any ideas how I can call express-validate validate function directly inside

(req, res) => {}

Upvotes: 1

Views: 854

Answers (1)

dimitris tseggenes
dimitris tseggenes

Reputation: 3186

What you can do is to run a check inside a custom validation. You should require validator as well.

const { check, body, param } = require('express-validator/check');
const { validator } = require('express-validator');

const checkValidation = () => {
  return [
    check('importantParam')
    .custom((value, {req}) => {
      const data = req.body;
      if (!validator.isEmail(data.username)) throw new Error("Not valid Email");
      if (!validator.isLength(data.password, {min:5})) throw new Error("Not valid password");
      // if importantParam is false, add the following properties to validation 
      if (!value) {
        if (!validator.isLength(data.firstname, {min:5})) throw new Error("Not valid firstname");
        if (!validator.isLength(data.lastname, {min:5})) throw new Error("Not valid lastname");
      } 
      return true;
  })
  ];
};

app.post('/user', checkValidation(), (req, res) => {
    //now below code can check for validation errors
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
        return res.status(422).json({ errors: errors.array() });
    }
    // do stuff here
});

Hope it helps!

Upvotes: 1

Related Questions