Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

281
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda