Search code examples
javascriptnode.jsexpressexpress-validator

How to make a single function for checking empty values


There is a router in which I want to check fields for empty values, but this can also be useful in other routers, how can I make one function to check the correct fields?

This is how it works: https://tppr.me/b8sSO, https://tppr.me/xm0mY

And I want something like this: https://tppr.me/FQ9IE, https://tppr.me/C6P2Y


Solution

  • Write a middleware to check the validation result.

    validation.js

    const { validationResult } = require('express-validator');
    const rules = require('./rules');
    
    const validate = (request, response, next) => {
      const errors = validationResult(request);
      if (errors.isEmpty()) {
        return next();
      }
      const extractedErrors = [];
      errors.array().map(err => extractedErrors.push({ [err.param]: err.msg }));
    
      return response.status(422).json({
        errors: extractedErrors,
      });
    }
    
    module.exports = {
      validate: validate,
      Rule: rules
    };
    

    and a file rules.js which contains all rules:

    const { body } = require('express-validator')
    
    function registerRule() {
      return [
    
        // username must be an email
        body('username')
          .not().isEmpty()
          .isEmail(),
          // .isLength({ min: 5 })
          // .withMessage('Username must have more than 5 characters'),
    
        // password must be at least 5 chars long
        body('password', 'Your password must be at least 5 characters')
          .not().isEmpty()
          .isLength({ min: 5 }),
      ];
    };
    
    module.exports = {
      Register: registerRule.call()
    };
    

    And use it like:

    const validation = require('./libs/validation');
    
    validate = validation.validate;
    ValidationRule = validation.Rule;
    
    router.post('/register', ValidationRule.Register, validate, (req, res, next) => {});
    

    I use this source to answer.