Search code examples
javascriptexpressendpointexpress-validator

Validating with express Validator's .equals()


I'm trying to validate a request to an endpoint, Using express validator's .equals() to check if user type's input is equal to 'savings' or 'current'. But the equals() only picks the first value.

I'm tried using the || statement

 const creatAccount = [

    check('type').not().isEmpty().withMessage('Please specify account type'),

    check('type').equals('savings' || 'current').withMessage('Invalid Account Type: Account Type can be either "savings" or "current"'),

    check('initialDeposit').not().isEmpty().withMessage('specify a Initial Deposit'),

    (req, res, next) => {

      const errors = validationResult(req);

      const errMessages = [];

      if (!errors.isEmpty()) {

        errors.array().forEach((err) => {

          errMessages.push(err.msg);

        });
        return res.status(401).json({
          status: 401,
          error: errMessages,
        });
      }
      return next();
    },
  ]

Solution

  • That is because

    'savings' || 'current'
    

    is first being resolved (as 'savings') and passed as a parameter to .equals(). Read more about how is that resolved || operator.

    There are a couple of options:

    const message = 'Invalid Account Type: Account Type can be either "savings" or "current"';
    check('type').equals('savings').withMessage(message);
    check('type').equals('current').withMessage(message);
    

    furthermore, you could move this to a function

    const validateType = type => {
       const message = 'Invalid Account Type: Account Type can be either "savings" or "current"';
       check('type').equals(type).withMessage(message);
    }
    validateType('savings');
    validateType('current');
    

    The recommended option

    Use oneOf

    const { check, oneOf } = require('express-validator/check');
    const message = 'Invalid Account Type: Account Type can be either "savings" or "current"';
    const creatAccount = [
    
        check('type').not().isEmpty().withMessage('Please specify account type'),
    
        oneOf([
           check('type').equals('savings'),
           check('type').equals('current'),
         ], message),
    
        check('initialDeposit').not().isEmpty().withMessage('specify a Initial Deposit'),
    
        (req, res, next) => {
    
          const errors = validationResult(req);
    
          const errMessages = [];
    
          if (!errors.isEmpty()) {
    
            errors.array().forEach((err) => {
    
              errMessages.push(err.msg);
    
            });
            return res.status(401).json({
              status: 401,
              error: errMessages,
            });
          }
          return next();
        },
      ]