Express Validator using 5.3.0 middleware function












0















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 .










share|improve this question





























    0















    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 .










    share|improve this question



























      0












      0








      0








      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 .










      share|improve this question
















      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 .







      express express-validator






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 19 '18 at 6:04







      codefreaK

















      asked Nov 14 '18 at 11:52









      codefreaKcodefreaK

      2,54431945




      2,54431945
























          1 Answer
          1






          active

          oldest

          votes


















          2





          +50









          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.






          share|improve this answer


























          • Might I suggest less misleading constant names? I mean if I see USERNAME_NOT_EMPTY, I would have expect, that the source of the error is that the username field is not empty.

            – mg30rg
            Nov 19 '18 at 9:14






          • 1





            @mg30rg fair point :D

            – robertklep
            Nov 19 '18 at 9:21











          • @robertklep currently its done using old api is there any downside of using the legacy api . This was a simple work around but precisely what I needed.

            – codefreaK
            Nov 19 '18 at 11:33











          • @codefreaK the documentation states that the legacy API shouldn't be used anymore because it won't receive new updates and may be removed in future releases.

            – robertklep
            Nov 19 '18 at 12:25











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53299625%2fexpress-validator-using-5-3-0-middleware-function%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          2





          +50









          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.






          share|improve this answer


























          • Might I suggest less misleading constant names? I mean if I see USERNAME_NOT_EMPTY, I would have expect, that the source of the error is that the username field is not empty.

            – mg30rg
            Nov 19 '18 at 9:14






          • 1





            @mg30rg fair point :D

            – robertklep
            Nov 19 '18 at 9:21











          • @robertklep currently its done using old api is there any downside of using the legacy api . This was a simple work around but precisely what I needed.

            – codefreaK
            Nov 19 '18 at 11:33











          • @codefreaK the documentation states that the legacy API shouldn't be used anymore because it won't receive new updates and may be removed in future releases.

            – robertklep
            Nov 19 '18 at 12:25
















          2





          +50









          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.






          share|improve this answer


























          • Might I suggest less misleading constant names? I mean if I see USERNAME_NOT_EMPTY, I would have expect, that the source of the error is that the username field is not empty.

            – mg30rg
            Nov 19 '18 at 9:14






          • 1





            @mg30rg fair point :D

            – robertklep
            Nov 19 '18 at 9:21











          • @robertklep currently its done using old api is there any downside of using the legacy api . This was a simple work around but precisely what I needed.

            – codefreaK
            Nov 19 '18 at 11:33











          • @codefreaK the documentation states that the legacy API shouldn't be used anymore because it won't receive new updates and may be removed in future releases.

            – robertklep
            Nov 19 '18 at 12:25














          2





          +50







          2





          +50



          2




          +50





          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.






          share|improve this answer















          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.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 19 '18 at 9:21

























          answered Nov 19 '18 at 7:55









          robertkleprobertklep

          137k18234244




          137k18234244













          • Might I suggest less misleading constant names? I mean if I see USERNAME_NOT_EMPTY, I would have expect, that the source of the error is that the username field is not empty.

            – mg30rg
            Nov 19 '18 at 9:14






          • 1





            @mg30rg fair point :D

            – robertklep
            Nov 19 '18 at 9:21











          • @robertklep currently its done using old api is there any downside of using the legacy api . This was a simple work around but precisely what I needed.

            – codefreaK
            Nov 19 '18 at 11:33











          • @codefreaK the documentation states that the legacy API shouldn't be used anymore because it won't receive new updates and may be removed in future releases.

            – robertklep
            Nov 19 '18 at 12:25



















          • Might I suggest less misleading constant names? I mean if I see USERNAME_NOT_EMPTY, I would have expect, that the source of the error is that the username field is not empty.

            – mg30rg
            Nov 19 '18 at 9:14






          • 1





            @mg30rg fair point :D

            – robertklep
            Nov 19 '18 at 9:21











          • @robertklep currently its done using old api is there any downside of using the legacy api . This was a simple work around but precisely what I needed.

            – codefreaK
            Nov 19 '18 at 11:33











          • @codefreaK the documentation states that the legacy API shouldn't be used anymore because it won't receive new updates and may be removed in future releases.

            – robertklep
            Nov 19 '18 at 12:25

















          Might I suggest less misleading constant names? I mean if I see USERNAME_NOT_EMPTY, I would have expect, that the source of the error is that the username field is not empty.

          – mg30rg
          Nov 19 '18 at 9:14





          Might I suggest less misleading constant names? I mean if I see USERNAME_NOT_EMPTY, I would have expect, that the source of the error is that the username field is not empty.

          – mg30rg
          Nov 19 '18 at 9:14




          1




          1





          @mg30rg fair point :D

          – robertklep
          Nov 19 '18 at 9:21





          @mg30rg fair point :D

          – robertklep
          Nov 19 '18 at 9:21













          @robertklep currently its done using old api is there any downside of using the legacy api . This was a simple work around but precisely what I needed.

          – codefreaK
          Nov 19 '18 at 11:33





          @robertklep currently its done using old api is there any downside of using the legacy api . This was a simple work around but precisely what I needed.

          – codefreaK
          Nov 19 '18 at 11:33













          @codefreaK the documentation states that the legacy API shouldn't be used anymore because it won't receive new updates and may be removed in future releases.

          – robertklep
          Nov 19 '18 at 12:25





          @codefreaK the documentation states that the legacy API shouldn't be used anymore because it won't receive new updates and may be removed in future releases.

          – robertklep
          Nov 19 '18 at 12:25


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53299625%2fexpress-validator-using-5-3-0-middleware-function%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Bressuire

          Vorschmack

          Quarantine