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:
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, ...], })