Tran B. V. Son
Tran B. V. Son

Reputation: 839

How to use express-validator middleware with routing-controllers typescript?

I'm moving my project from javascript to typescript and I found routing-controllers is a great package for routing, but I'm not sure how to use express-validator middleware with routing-controllers? For example, in my js project, when I want to validate username and password:

app.post('/user', [
  // username must be an email
  check('username').isEmail(),
  // password must be at least 5 chars long
  check('password').isLength({ min: 5 })
], (req, res) => {
  // Finds the validation errors in this request and wraps them in an object with handy functions
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(422).json({ errors: errors.array() });
  }
});

How can I do that with routing-controllers ?

@JsonController()
export class UserController {
  @Post("/users")
  async post(@Req() req: Request, @Res() res: Response) {
  }
}

Thank you very much!


I see somebody are using class-validator, but that package validate in model layer, I want to validate request from client first.

Upvotes: 1

Views: 5614

Answers (1)

DimaIT
DimaIT

Reputation: 135

You can use @UseBefore decorator for express middlewares in routing-controllers. For your example:

@JsonController()
export class UserController {
  @Post("/users")
  @UseBefore(
    check('username').isEmail(),
    check('password').isLength({ min: 5 })
  )
  async post(@Req() req: Request, @Res() res: Response) {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(422).json({ errors: errors.array() });
    }
  }
}

However I would still recommend to look at class-validator for request validation. It better fits typescript and integrated into routing-controllers. Here your example with class-validator:

class User {
  @IsEmail()
  username: string;

  @MinLength(5)
  password: string;
}

@JsonController()
export class UserController {
  @Post("/users")
  async post(@Body() user: User, @Res() res: Response) {
  }
}

Check docs for more details.

Upvotes: 1

Related Questions