Created
April 27, 2023 15:16
-
-
Save gritzkoo/d68e14e68fccb1d726565dc28afc2397 to your computer and use it in GitHub Desktop.
example to recreate Laravel exists validation in nestjs using class-validation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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`; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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