Home > Software engineering >  Nest.js unique dto validator
Nest.js unique dto validator

Time:05-03

Maybe someone know how to make custom unique validator with class-validator in nest.js.I found few articles in internet, but however those implementations was not reusable. I wanna my unique validator reuse in every dto for example: users, products.

CodePudding user response:

You can use this small lib to reach your goal or get inspired by it's code dbvalidator,

to use it, you only need to, install it npm install @youba/nestjs-dbvalidator

2/ register it :

 @Module({
  imports: [DbValidatorsModule.register({
    type: 'mysql',
    host:  "localhost",
    port: 3306,
    username:"root",
    password:"password",
    database:"demo"})],
  providers: [StreetService],
  controllers: [StreetController],
})
export class StreetModule {
  constructor() {}
}

3/ use it in DTO :

@IsNotEmpty()
@Validate(IsUnique, 
[ { table: "company", column: "name" }] )

name: string;

ps:I'm the author in case you need any explanation

  • Related