Search code examples
typescriptnestjsclass-validator

Matches decorator of class-validator does not work correctly


I'm learning nestjs as my job requirement

here is my regex: /(?=[^\d].*)^[\w]{4,}$/ which means the first character must not be a number, at least 4 characters for the whole string

here the 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;
}

whatever the username in the request body is, it still passed, even an empty string but when I post a plain number for the username field, the server responded an error as default action of the Matches decorator

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

I have also enabled Validation in main.ts

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

could anyone explain for me? thanks for your help


Solution

  • weirdly, I've resolved this problem by deleting dist folder

    maybe ts transpiler did not re-transpile the newest ts code to js code. I have no reason why