Search code examples
node.jsexpressexpress-validator

Troubles with express-validator isIn


I started a simple tic tac toe game node project to learn more about the backend. The problem appeared when I tried to implement validation of the game create request. It contains the only chose player symbol, which obviously should be "x" either "o". Unfortunately, requests keep passing validation, and mongoose every time throws "ValidatorError: z is not a valid enum value for path symbol"

Here's the req's body:

{
    "symbol": "z"
}

Here's the req's route code:

GameRouter.post(
  '/',
  body('symbol')
    .exists()
    .notEmpty()
    .isIn(['x', 'o']),
  authMiddleware,
  GameController.createGame
);

Here's the express middlewares:

const app = express();

app.use(express.json());
app.use(cookieParser());
app.use(cors());
app.use('/auth', AuthRouter);
app.use('/users', UserRouter);
app.use('/game', GameRouter);
app.use(errorMiddleware);

Solution

  • The solution is simple, I just forgot to check validation result in my controller function. I thought validation works but it was manual check if(!symbol):

    async createGame(req, res, next) {
        try {
          const errors = validationResult(req);
          if (!errors.isEmpty()) {
            return next(ApiError.BadRequest('Validation error', errors.array()));
          }
         ...
        } catch (e) {
          next(e);
        }
      }