Home > Software design >  express-validator: is it possible to chain different user validation rules?
express-validator: is it possible to chain different user validation rules?

Time:12-21

I have the following rules which are almost similar except for one route the param is optional and the other it is mandatory. need to combine them so that i can use single code interchangeably for mandatory condition and other for optional condition

Is there a way to combine them so that I don't have redundant code?

const pathParamValidation = check('convertedUrlId')
  .isLength({ min: 5, max: 6 })
  .withMessage({
    error: 'Invalid length',
    detail: {
      convertedUrlId:
        'Invalid Length! Character length >=5 and <7 characters are allowed',
    },
  })
  .matches(/^[~A-Za-z0-9/./_/-]*$/)
  .withMessage({
    error: 'Invalid characters',
    detail: {
      convertedUrlId:
        'Invalid characters! Only [A-Z],[a-z],[0-9], _ , - , . , ~ are allowed',
    },
  });

#optional

const optionalConvertedUrlIdValidation = check('convertedUrlId')
  .optional()
  .matches(/^[~A-Za-z0-9/./_/-]*$/)
  .withMessage({
    error: 'Invalid characters',
    detail: {
      convertedUrlId:
        'Invalid characters! Only [A-Z],[a-z],[0-9], _ , - , . , ~ are allowed',
    },
  })
  .isLength({ min: 5, max: 6 })
  .withMessage({
    error: 'Invalid length',
    detail: {
      convertedUrlId:
        'Invalid Length! Character length >=5 and <7 characters are allowed',
    },
  });

I tried combining in this way, but no luck

const checkConvertedUrlSchema = check('convertedUrlId')
  .matches(/^[~A-Za-z0-9/./_/-]*$/)
  .withMessage({
    error: 'Invalid characters',
    detail: {
      convertedUrlId:
        'Invalid characters! Only [A-Z],[a-z],[0-9], _ , - , . , ~ are allowed',
    },
  });

const checkConvertedUrlLength = check('convertedUrlId')
  .isLength({ min: 5, max: 6 })
  .withMessage({
    error: 'Invalid length',
    detail: {
      convertedUrlId:
        'Invalid Length! Character length >=5 and <7 characters are allowed',
    },
  });

const convertedUrlIdValidation =
  check('convertedUrlId').checkConvertedUrlLength.checkConvertedUrlSchema;
const optionalConvertedUrlIdValidation =
  check('convertedUrlId').optional().checkConvertedUrlSchema
    .checkConvertedUrlLength;

CodePudding user response:

You can create a validator factory to create the common validation rules.

import { body, validationResult } from 'express-validator';
import express from 'express';
const app = express();

const convertedUrlIdValidationFactory = () =>
  body('convertedUrlId')
    .isLength({ min: 5, max: 6 })
    .withMessage({
      error: 'Invalid length',
      detail: {
        convertedUrlId: 'Invalid Length! Character length >=5 and <7 characters are allowed',
      },
    })
    .matches(/^[~A-Za-z0-9/./_/-]*$/)
    .withMessage({
      error: 'Invalid characters',
      detail: {
        convertedUrlId: 'Invalid characters! Only [A-Z],[a-z],[0-9], _ , - , . , ~ are allowed',
      },
    });

app.use(express.json());
app.post('/optional', convertedUrlIdValidationFactory().optional(), (req, res) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
  }
  console.log(req.body);
  res.sendStatus(200);
});

app.post('/required', convertedUrlIdValidationFactory(), (req, res) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
  }
  console.log(req.body);
  res.sendStatus(200);
});

app.listen(3000, () => console.log('server started at port 3000'));

Test case 1: there is no convertedUrlId data.

 ⚡  curl -X POST http://localhost:3000/required
{"errors":[{"msg":{"error":"Invalid length","detail":{"convertedUrlId":"Invalid Length! Character length >=5 and <7 characters are allowed"}},"param":"convertedUrlId","location":"body"}]}%

⚡  curl -X POST http://localhost:3000/optional
OK%  

Test case 2: there is a convertedUrlId data.

⚡  curl -X POST -H "Content-Type: application/json" --data '{"convertedUrlId": "12345"}' http://localhost:3000/required
OK% 

⚡  curl -X POST -H "Content-Type: application/json" --data '{"convertedUrlId": "12345"}' http://localhost:3000/optional
OK%

CodePudding user response:

This worked for me

const checkConvertedUrlSchema = (chain) =>
  chain.matches(/^[~A-Za-z0-9/./_/-]*$/).withMessage({
    error: 'Invalid characters',
    detail: {
      convertedUrlId:
        'Invalid characters! Only [A-Z],[a-z],[0-9], _ , - , . , ~ are allowed',
    },
  });

const checkConvertedUrlLength = (chain) =>
  chain.isLength({ min: 5, max: 6 }).withMessage({
    error: 'Invalid length',
    detail: {
      convertedUrlId:
        'Invalid Length! Character length >=5 and <7 characters are allowed',
    },
  });

const checkConvertedUrlIdBodyValidation = (chain) =>
  chain
    .not()
    .isEmpty()
    .withMessage({
      error: 'Invalid Request Body',
      detail: {
        convertedUrlId:
          'Request Syntax Error! convertedUrlId parameter is required',
      },
    });

const convertedUrlIdBodyValidation = checkConvertedUrlLength(
  checkConvertedUrlSchema(
    checkConvertedUrlIdBodyValidation(check('convertedUrlId'))
  )
);

const convertedUrlIdValidation = checkConvertedUrlLength(
  checkConvertedUrlSchema(check('convertedUrlId'))
);
const optionalConvertedUrlIdValidation = convertedUrlIdValidation.optional();
  • Related