question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

So the only way to validate with v6 is cluttering my routes???

See original GitHub issue

Previously I applied validation as a middleware like so which is much cleaner… router.post('/signup', userSignupValidator, signup);

exports.userSignupValidator = (req, res, next) => {
    req.check('name', 'Name is required').notEmpty();
    req.check('email', 'Email must be between 3 to 32 characters')
        .matches(
            /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/
        )
        .withMessage('Please type your valid email address')
        .isLength({
            min: 4,
            max: 32
        });

    req.check('password', 'Password is required').notEmpty();
    req.check('password')
        .isLength({ min: 6 })
        .withMessage('Password must contain at least 6 characters')
        .matches(/\d/)
        .withMessage('Password must contain a number');
    const errors = req.validationErrors();
    if (errors) {
        const firstError = errors.map(error => error.msg)[0];
        return res.status(400).json({ error: firstError });
    }
    next();
};

But it does not work with version 6. So the only way to validate is cluttering my routes like so… as shown in documentation???

app.post('/user', [
  // username must be an email
  check('username').isEmail(),
  // password must be at least 5 chars long
  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));
});

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:1
  • Comments:11 (3 by maintainers)

github_iconTop GitHub Comments

6reactions
rubiincommented, Aug 6, 2019

I dont like to be limited with only one way or style of validating things too. Before 6.x , I used to mount the express validator as a middleware and write a validation function which then was added onto the routes. The whole point of doing this was to maintain the code readability and make it look cleaner. Now we have to add all the validations on the routes itself and if there are tons of validations, the route looks lot more like a way big function and there goes your readability

2reactions
caubcommented, Aug 27, 2019

Ideally this library shouldn’t even write to req

I’d like to do something like:

const validateUser = async (req, res, next) {
	try {
		await validate({
			username: isEmail().run(req),
			password: isEmpty().run(req),
		});
	} catch (err) {
		return res.status(422).json({ errors: err.errors });
	}
	next();
}
app.post('/create-user', validateUser, (req, res) => {
	// this is guaranteed to run only when request is valid
	// proceed with user creation
	userController.createUser(req);
});
Read more comments on GitHub >

github_iconTop Results From Across the Web

React Router 6: Authentication
You will learn how to use authentication in React Router 6 by authenticating a user by login (sign in) and logout (sign out)...
Read more >
Best practices for route validation?
The current way I'm doing it, is really cluttering my code up and I'm wondering if there's a better way of doing it...
Read more >
validate params then navigate with React Router v6
I want to validate the params in my component and do a redirect if they don't pass some logic. Two things can go...
Read more >
React Router v6
So as you added more routes, your bundle just kept growing. Also, the <Route component> prop made it difficult to pass custom props...
Read more >
Day One: Beginner's Guide to Learning Junos
How routing works within Junos, not only on a default protocol ... The Appendix will help you to set up your own virtual...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found