Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

custom() validation not working #505

Closed
KrashLeviathan opened this issue Jan 23, 2018 · 9 comments
Closed

custom() validation not working #505

KrashLeviathan opened this issue Jan 23, 2018 · 9 comments

Comments

@KrashLeviathan
Copy link

Here's an abstract of the code I'm working with:

import { check } from 'express-validator/check';

router.post(
  '/myendpoint',
  [
    check('myparameter', 'This should be hardcoded to fail')
      .custom((value, { req }) => {
        console.log(value);
        return false;
      })
  ],
  myEndpointHandler
);

I'm using a custom check to validate a query parameter, and after trying everything to get it to work, I distilled it down to something that looks just like the code in the documentation, and it still won't work. It's not asynchronous, it's just a boolean check. I took out my boolean check and hardcoded in false, but it still doesn't work. I'm running it with v4.3.0. I added the console.log(value) and it's printing the correct value that gets passed in. Is there something I'm missing, or is custom() not fully working, or is the documentation out of date?

Thanks!

@gustavohenke
Copy link
Member

How are your requests being made?

@KrashLeviathan
Copy link
Author

KrashLeviathan commented Jan 23, 2018

HTTP POST request via Firefox RESTClient using Content-Type: application/json header. The body of the request is { "myparameter": "some value" }.

@gustavohenke
Copy link
Member

This isn't sounding good.
Can you share a minimal reproducible project, so I can see if there's anything with your setup?

@valentincostam
Copy link

valentincostam commented Jan 26, 2018

I'm struggling with the exact same problem! I just asked a question on StackOverflow about it. 🤦‍♂️

I'm using a custom validation just like @KrashLeviathan does:

router.post('/person/add',
  personController.validateData, 
  asyncHandler(personController.createPerson)
)
exports.validateData = [

  // ...Other built-in validations that work...

  body('field')
    .custom((value) => {
      console.log('This message shows up!')
      return false
    })
    .withMessage('Wrong!'),

  // ...Other built-in validations that work...
]

I never get the 'Wrong!' flash message.

Any idea why this is happening? I don't actually know how to debug it. 😞

Update: @gustavohenke This is my project repo and this is the line of my above example. It's not that minimal project you're asking for but it's not that much large (it has just one controller with CRUD operations). Worth say that requests are made successfully and the rest of validations are working fine.

@KrashLeviathan
Copy link
Author

Sure. The project is open source, so you can take a look at the project setup here: https://github.com/hammer-io/yggdrasil. (It's still very much under development, so take things with a grain of salt!) The endor folder has our backend code, and that's where I was trying to run the validation. I ended up using a regular node validation construct instead of using check. The place I was trying to use it was in endor/src/routes/invites.routes.js, in the POST endpoint to invite a new contributor. We usually have all the validation in middleware, but when I was trying to debug it I essentially replaced the route at approx. line 105 with the following:

router.post(
  '/projects/:projectId/invites/:user',
  [
    check('daysFromCreationUntilExpiration', 'This should be hardcoded to fail')
      .custom((value, { req }) => {
        console.log(value);
        return false;
      })
  ],
  invitesController.addInviteToProject
);

I hope that's enough information to try to track down the issue (or to point out what I was doing wrong). :-)

@gustavohenke
Copy link
Member

Hey guys, so I checked both of your codes and they both work.

@valeco I added a console.log(req.flash()) to your error handler and it prints all messages, including Wrong! 😉

@KrashLeviathan I replaced that route with the following:

router.post(
  '/foo',
  // authController.isAuthenticated,
  check('daysFromCreationUntilExpiration', 'This should be hardcoded to fail')
      .custom((value, { req }) => {
        console.log(value);
        return false;
      }),
  (req, res, next) => {
    const errors = validationResult(req).mapped();
    res.json({ errors });
  }
);

You were probably missing the call to validationResult.

Will close the issue for now. Feel free to continue the discussion.

@valentincostam
Copy link

valentincostam commented Jan 27, 2018

Hey @gustavohenke, thank you so much for spend your time on this and for your quick response!

You're right, the Wrong! message is printed but only when another validation fail (at least one of them), otherwise custom validation gets ignored (as if the return false wasn't there).

In my case, if you fill the fields nombre, horas and ano, the Wrong! message doesn't appear. You can try it in your browser on localhost:3000/materias/agregar. (Flash messages are printed between the curly brackets above the form.)

@gustavohenke
Copy link
Member

Sorry @valeco but I still can't reproduce. I commented out the other validators and sanitisers and it still works. I must also comment that I had to remove the mongoose connection.

Can you please create a minimal example that reproduces your issue?

@lock
Copy link

lock bot commented May 31, 2019

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

@lock lock bot locked as resolved and limited conversation to collaborators May 31, 2019
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants