Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

128
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!