如何在 nestjs 中使用正则表达式进行验证?

How to use regexp for validate in nestjs?

我想在 nestjs 中使用正则表达式进行验证。

例如:

正则表达式

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

方法

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

  }

我能用什么? 验证管道?

我会创建一个 DTO class 就像

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

然后您可以在路由处理程序中使用它,例如

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

}

然后只要你用ValidationPipe就可以了。任何不匹配的都会导致 400 BadRequest