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

130
Visualizações
HTTP Post with request body failed when using Regex to validate body parameter

I'm testing an Express API using the post method.

The request body is like

{
    "menuId": "id2-test",
    "menuName": "test menu name 2",
    "menuUrl": "/admin/menu/test",
    "desc": "this is test menu 2 description",
    "menuOrder": 2,
    "usageStatus": "true" 
}

As you could see there is a property menuUrl which is a path of a valid URL. So to make sure user can enter the valid value for all provided properties. I've tried to validate the menuUrl using Regex

router.post(
  "/",
  validate(paramValidation.createMenu),
  async (req, res, next) => {
    const { userInfo } = req;
    const menu = new Menus({
      menuUrl: req.body.menuUrl,
      ...req.body,
    });

    // Regex validation is here
    if (!menu?.menuUrl.match(/^[a-z][a-z0-9+.-]*:/)) {
      return new ApiError("MENU_URL_NOT_VALID", httpStatus.BAD_REQUEST, true);
    }

    menu.createdBy = userInfo.userNm;

    await Menus.findOne({ menuId: menu.menuId })
      .then((_menu) => {
        if (!_menu) {
          return menu.save();
        }
        const err = new ApiError("ROLE_ALREADY", httpStatus.BAD_REQUEST, true);
        return Promise.reject(err);
      })
      .then((_menu) => {
        res.status(httpStatus.CREATED).json(_menu);
        return null;
      })
      .catch((e) => next(e));
  }
);

However, When the request is made, I received the error that said that could not get response. If I remove the Regex validation step above, and then everything still working fine. What happened with that?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

The regular expression pattern you seem to want here is something like:

 ^/[az][a-z0-9+.-]*(?:/[az][a-z0-9+.-]*)*$

Updated code:

 if (!menu?.menuUrl.match(/^\/[az][a-z0-9+.-]*(?:\/[az][a-z0-9+.-]*)*$/)) { return new ApiError("MENU_URL_NOT_VALID", httpStatus.BAD_REQUEST, true); }
over 4 years ago · Santiago Trujillo 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