Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

274
Vistas
express-validator: is it possible to chain different user validation rules?

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;
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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%
about 4 years ago · Juan Pablo Isaza Denunciar

0

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();
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda