You are currently viewing Nestjs “IsUnique” validation (custom validator with database query) for email, username, or any column or field
Nestjs custom validation codes

Nestjs “IsUnique” validation (custom validator with database query) for email, username, or any column or field

  • Post category:Node.js
  • Post last modified:November 1, 2023
  • Reading time:2 mins read

In this tutorial, we’re going to implement IsUnique custom validation in Nestjs to check if a database value (e.g. email, username, etc.) is unique or not, using class-validator.

We’ll see how to query the database in our custom validator and how to create a custom decorator for the validator.

The video tutorial walks you through step by step how to implement this but here is the summary of some of the codes:

https://youtu.be/Ey8QOhXKW8s

Here is the git repository for the project: nestjs-is-unique-validation

Dependency Injection

To query the database, we make use of the EntityManager from Typeorm via dependency injection, which we can Nestjs handle for use.

constructor(private readonly entityManager: EntityManager) {}

But for the dependency injection to happen, we need to do this additional configuration in main.ts file:

// main.ts
useContainer(app.select(AppModule), { fallbackOnErrors: true });

Also, we need to include the custom validation constraint in the providers array in AppModule,

// app.module.ts
@Module({
  ...
  providers: [AppService, IsUniqueConstraint, ...],
})

Leave a Reply