【问题标题】:Matches decorator of class-validator does not work correctly匹配类验证器的装饰器无法正常工作
【发布时间】:2021-06-30 12:20:23
【问题描述】:

我正在学习nestjs作为我的工作要求

这是我的正则表达式:/(?=[^\d].*)^[\w]{4,}$/,这意味着第一个字符不能是数字,整个字符串至少 4 个字符

这里是 DTO:

import { IsString, IsPhoneNumber, Matches } from 'class-validator';
export class CreateUserDto {
  @Matches(/(?=[^\d].*)^[\w]{4,}$/, {
    message:
      'the first character of the username must not be a number. Username must contains at least 4 characters',
  })
  username: string;

  @IsString()
  password: string;

  @IsPhoneNumber('VN')
  phoneNumber: string;
}

无论请求正文中的用户名是什么,它仍然通过,即使是一个空字符串 但是当我为用户名字段发布一个普通数字时,服务器响应了一个错误作为匹配装饰器的默认操作

{
    "statusCode": 400,
    "message": [
        "username must be a string"
    ],
    "error": "Bad Request"
}

我还在 main.ts 中启用了验证

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.enableCors();
  app.useGlobalPipes(new ValidationPipe());
  await app.listen(9000);
}
bootstrap();

谁能帮我解释一下?感谢您的帮助

【问题讨论】:

  • 您的意思是至少四个字符而不是单词?
  • 另外,不仅匹配的字符串不能是数字。它也不能以数字开头,例如333jjj 将不匹配。
  • 究竟是什么问题?
  • 以前,我无法使用 Matches 装饰器通过正则表达式验证用户名字段。但在删除dist 文件夹后。它就像一个魅力。实际上,我刚刚解决了我的问题。无论如何,感谢您的关注:)
  • 哦,是的,我的意思是“字符”。这是我的拼写错误

标签: typescript nestjs class-validator


【解决方案1】:

奇怪的是,我通过删除 dist 文件夹解决了这个问题

也许 ts 转译器没有将最新的 ts 代码重新转译为 js 代码。我没有理由这样做

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-17
    • 2021-01-06
    • 2020-04-19
    • 2015-11-09
    • 1970-01-01
    相关资源
    最近更新 更多