Vladimir  Golub
Vladimir Golub

Reputation: 613

How to use regexp for validate in nestjs?

I want to use regexp in validation in nestjs.

For example:

RegExp

pagePattern    = '[a-z0-9\-]+';

Method

  @Get('/:article')
  getIndex(
   @Param('article')
  ) {

  }

What can I use? ValidationPipe?

Upvotes: 4

Views: 12300

Answers (2)

PovarCoda
PovarCoda

Reputation: 9

@Matches(new RegExp('^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*).+$'), {
    message: 'qwe',
  })

Upvotes: 0

Jay McDoniel
Jay McDoniel

Reputation: 70221

I would create a DTO class like

class ArticleParamDTO {
  @Matches('[a-z0-9\-]+') // comes from class-validator
  article: string;
}

And then you can use it in the route handler like

@Get(':article')
getIndex(@Param() { article }: ArticleParamDto) {

}

And then as long as you use the ValidationPipe it will all work. Anything that doesn't match will cause a 400 BadRequest

Upvotes: 13

Related Questions