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

278
Vistas
express-validator: ¿es posible encadenar diferentes reglas de validación de usuarios?

Tengo las siguientes reglas que son casi similares, excepto por una ruta, el parámetro es opcional y el otro es obligatorio . necesito combinarlos para que pueda usar un solo código indistintamente para la condición obligatoria y otro para la condición opcional

¿Hay alguna manera de combinarlos para que no tenga un código redundante?

 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 [AZ],[az],[0-9], _ , - , . , ~ are allowed', }, });

#opcional

 const optionalConvertedUrlIdValidation = check('convertedUrlId') .optional() .matches(/^[~A-Za-z0-9/./_/-]*$/) .withMessage({ error: 'Invalid characters', detail: { convertedUrlId: 'Invalid characters! Only [AZ],[az],[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', }, });

Intenté combinar de esta manera, pero no tuve suerte.

 const checkConvertedUrlSchema = check('convertedUrlId') .matches(/^[~A-Za-z0-9/./_/-]*$/) .withMessage({ error: 'Invalid characters', detail: { convertedUrlId: 'Invalid characters! Only [AZ],[az],[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

Puede crear una fábrica de validadores para crear las reglas de validación comunes.

 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 [AZ],[az],[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'));

Caso de prueba 1: no hay datos de convertedUrlId .

 ⚡ 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%

Caso de prueba 2: hay datos de convertedUrlId .

 ⚡ 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

esto funcionó para mí

 const checkConvertedUrlSchema = (chain) => chain.matches(/^[~A-Za-z0-9/./_/-]*$/).withMessage({ error: 'Invalid characters', detail: { convertedUrlId: 'Invalid characters! Only [AZ],[az],[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