nest custom class validator

Solutions on MaxInterview for nest custom class validator by the best coders in the world

showing results for - "nest custom class validator"
Joaquín
12 Oct 2020
1class-validator
Clelia
21 Jun 2019
1useContainer(app.select(AppModule), { fallbackOnErrors: true });
2
3@ValidatorConstraint({ name: 'UserExists', async: true })
4@Injectable()
5export class UserExistsRule implements ValidatorConstraintInterface {
6  constructor(private usersRepository: UsersRepository) {}
7
8  async validate(value: number) {
9    try {
10      await this.usersRepository.getOneOrFail(value);
11    } catch (e) {
12      return false;
13    }
14
15    return true;
16  }
17
18  defaultMessage(args: ValidationArguments) {
19    return `User doesn't exist`;
20  }
21}
22
23export function UserExists(validationOptions?: ValidationOptions) {
24  return function (object: any, propertyName: string) {
25    registerDecorator({
26      name: 'UserExists',
27      target: object.constructor,
28      propertyName: propertyName,
29      options: validationOptions,
30      validator: UserExistsRule,
31    });
32  };
33}
34
35