express validator : how to check for "+xyz" using query check?

Viewed 191

i am trying to validate/allow set of words like +originalUrl, -originalUrl , +createdAt using express-validator.

it supports .matches which allows patterns. https://github.com/validatorjs/validator.js/

this is my pattern

query('sort_by')
    .optional()
    .matches(/^(+originalUrl|-originalUrl)$/)
    .withMessage({
      error: 'Invalid parameter value',
      detail: {
        max_results: 'parameter value (+originalUrl|-originalUrl) is allowed',
      },
    }),

tried .matches(/^(\+originalUrl|-originalUrl)$/) but it didnt worked.

Somehow I feel there is a problem with reading "+". In my backend + is encoded as %20, so tried replacing + with %20 but no luck.

Update: upon logging query params + is treated as ' orignalUrl' and .isIn([' orginalUrl'] works now, butstill how do i transform or query on + because somebody can input ' originalUrl' this will still work , hence getting validated which is not desirable.

tried asking validator folks too -> https://github.com/express-validator/express-validator/issues/1122

how do i check for +something ?

1 Answers

send it as %20 and do an unescape

query('sort_by')
.optional()
.unescape()
.matches(/^(+originalUrl|-originalUrl)$/)
.withMessage({
  error: 'Invalid parameter value',
  detail: {
    max_results: 'parameter value (+originalUrl|-originalUrl) is allowed',
  },
})
Related