Skip to content

Instantly share code, notes, and snippets.

@gritzkoo
Created April 27, 2023 15:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gritzkoo/d68e14e68fccb1d726565dc28afc2397 to your computer and use it in GitHub Desktop.
Save gritzkoo/d68e14e68fccb1d726565dc28afc2397 to your computer and use it in GitHub Desktop.
example to recreate Laravel exists validation in nestjs using class-validation
import { ValidatorConstraint, ValidatorConstraintInterface, ValidationArguments } from 'class-validator';
import { Injectable } from '@nestjs/common';
import { Repository } from 'typeorm';
@ValidatorConstraint({ name: 'exists', async: true })
@Injectable()
export class ExistsValidator implements ValidatorConstraintInterface {
constructor(private readonly repository: Repository<any>) {}
async validate(value: any, args: ValidationArguments) {
const [entityClass, condition] = args.constraints;
const result = await this.repository.findOne(entityClass, { where: condition(value) });
return !!result;
}
defaultMessage(args: ValidationArguments) {
const [entityClass] = args.constraints;
return `${entityClass.name} not found`;
}
}
import { IsNotEmpty, Validate } from 'class-validator';
import { ExistsValidator } from './exists.validator';
import { User } from './user.entity';
export class CreateUserDto {
@IsNotEmpty()
name: string;
@Validate(ExistsValidator, [User, (value) => ({ email: value })])
email: string;
}
import { Module } from '@nestjs/common';
import { ExistsValidator } from './exists.validator';
@Module({
providers: [ExistsValidator],
})
export class ValidationModule {} // remember to import in AppModule ;)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment