Search code examples
duplicatesnestjstypeormdto

How to validate duplicates in nestjs dto?


In the Nest js create dto I receive two properties name and age. I need to validate if user with name and age already exists should trough 400 error "duplicate values". Like in table we have name: "John", age: 20 and we create user with the same value/combination "John" and 20, it should show error. I tried to use validation check NameExists but do not know how to take values for both, I only take for one. https://dev.to/avantar/custom-validation-with-database-in-nestjs-gao

@IsNotEmpty({
    message: 'Name is missing',
  })
  @MinLength(5, {
    message: 'Name is too short. Select name longer than 5 characters.',
  })
  @UserExists()
  name: string;

@IsNotEmpty({
    message: 'Age is missing.',
  })
  @IsInt()
  @Transform(({ value }) => Number(value))
  age: number;


Solution

  • In this example, you could see how to access other properties of the object in your custom decorator. https://github.com/typestack/class-validator#custom-validation-decorators

    However, my choice, in this case, would be to create proper unique indexes in the database and handle the DB error as you could encounter race conditions if 2 requests will come with the same user name and age at the same time.