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(app.select(AppModule), { fallbackOnErrors: true });

@ValidatorConstraint({ name: ‘UserExists’, async: true })
@Injectable()
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) {
registerDecorator({
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]

0
inline scripts encapsulated in