nest custom class validator

The solution for “nest custom class validator” can be found here. The following code will assist you in solving the problem.

useContainer(, { fallbackOnErrors: true });

@ValidatorConstraint({ name: ‘UserExists’, async: true })
export class UserExistsRule implements ValidatorConstraintInterface {
constructor(private usersRepository: UsersRepository) {}

async validate(value: number) {
try {
await this.usersRepository.getOneOrFail(value);
} catch (e) {
return false;

return true;

defaultMessage(args: ValidationArguments) {
return `User doesn’t exist`;

export function UserExists(validationOptions?: ValidationOptions) {
return function (object: any, propertyName: string) {
name: ‘UserExists’,
target: object.constructor,
propertyName: propertyName,
options: validationOptions,
validator: UserExistsRule,

Thank you for using DeclareCode; We hope you were able to resolve the issue.

More questions on [categories-list]

inline scripts encapsulated in