Here we will learn how to validate user input

// INSTALL EXPRESS VALIDATOR 
npm i express-validator

// routes/auth.js
const expValidator = require("express-validator/check")
router.post("/signup", check('email')
	.isEmail()
	.withMessage('Enter valid email'),
	authController.postSignup);

// controller/auth.js
const { validationResult } = require("express-validator/check")
exports.postSignup = (req, res, next) => {
    ...
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
        return res.status(422).render("auth/signup", {
            path: '/signup',
            pageTitle: 'Signup',
            errorMessage: errors.array()
        })
    }

    User.findOne({ email: email }).then(userData => {

On peux egalement ajouter des custom validators

.custom((value, {req}) => {
        if(value !== "[email protected]") {
            throw new Error('This email is forbidden')
        }
	return true
    })),
router.post(
  '/login',
  [
    body('email')
      .isEmail()
      .withMessage('Please enter a valid email address.')
// to remove whitespaces and Maj
      .normalizeEmail(),
    body('password', 'Password has to be valid.')
      .isLength({ min: 5 })
      .isAlphanumeric()
// to remove whitespaces
      .trim()
  ],
  authController.postLogin
);

router.post(
    '/signup',
    [
      check('email')
        .isEmail()
        .withMessage('Please enter a valid email.')
        .custom((value, { req }) => {
          return User.findOne({ email: value }).then(userDoc => {
            if (userDoc) {
              return Promise.reject(
                'E-Mail exists already, please pick a different one.'
              );
            }
          });
        }),
      body(
        'password',
        'Please enter a password with only numbers and text and at least 5 characters.'
      )
        .isLength({ min: 5 })
        .isAlphanumeric(),
      body('confirmPassword').custom((value, { req }) => {
        if (value !== req.body.password) {
          throw new Error('Passwords have to match!');
        }
        return true;
      })
    ],
    authController.postSignup
  );