Search code examples
expressexpress-validator

Express Validator using 5.3.0 middleware function


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

const session = require('express-session');

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

app.use(session({
    secret: 'keyboard cat',
    resave: false,
    saveUninitialized: true,
    cookie: { secure: false }
}))
app.get("/test", [
    // username must be an email
    check('username').not().isEmpty(),`//.withCustomMessage() based on the content of req.session`
    // password must be at least 5 chars long
    check('password').not().isEmpty()
],(req,res)=>{
    console.log("req.session", req.session);
    // 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() });
    }
    //console.log("req.session",req.session);
});

app.get("/",(req,res,next)=>{
  req.session.message  = "beoulo ";
 // console.log(req.session);
  res.status(200).json({
      "status" :"session set"
  });
});

app.listen(3000,()=>{
    console.log("Listening on port 3000!!!");
});

Is passing Check directly as middleware the only way to use it .? Can we still use req.checkbody(field,errormessage) format or something equivalent inside a seperate middleware function cause the error message has to be taken from the session

I want to access a variable from req.session and based on that generate a custom error message

previous implementation worked fine as it used req.checkBody()

with new changes what should I do to handle this scenario .


Solution

  • You can rewrite the default error messages inside of your own handler.

    Assuming that your error messages are stored in req.session.errors, and that this is an object that maps a particular validation to a particular error message.

    For instance:

    // req.session.errors =
    {
      "USERNAME_EMPTY" : "The username cannot be empty",
      "PASSWORD_EMPTY" : "The password cannot be empty",
    }
    

    Next, you would provide custom messages for each validation, that match the keys of the abovementioned object:

    check('username').not().isEmpty().withMessage('USERNAME_EMPTY')
    check('password').not().isEmpty().withMessage('PASSWORD_EMPTY')
    

    Finally, inside your handler, you perform a lookup from the validation errors to the error message values:

    if (! errors.isEmpty()) {
      const list = errors.array();
    
      list.forEach(error => {
        error.msg = req.session.errors[error.msg] || error.msg;
      });
    
      return res.status(422).json({ errors: list });
    }
    

    Or just depend on an older version of express-validator so you can keep using the legacy API.