Search code examples
nestjsemail-validationclass-validator

Email verification with class-validator in nestJS


What i'm trying to do is propagate an error when some one tries to sign up with an email that's already in use. By default this returns a 500 error, but i need it to throw a meaningful error for this particular scenario. Note: The program returns a 500 error for every error


Solution

  • Yes, this is possible to validate email using class-validator

    First of all you need to create custom class for this validator like this for example.

    @ValidatorConstraint({ name: 'isEmailUserAlreadyExist', async: true })
        @Injectable()
        export class IsEmailUserAlreadyExistConstraint
          implements ValidatorConstraintInterface
        {
          constructor(protected readonly usersService: UsersService) {}
        
          async validate(text: string) {
            return !(await this.usersService.userExists({
              email: text,
            }));
          }
        }
        
        export function IsEmailUserAlreadyExist(validationOptions?: ValidationOptions) {
          return function (object: any, propertyName: string) {
            registerDecorator({
              target: object.constructor,
              propertyName: propertyName,
              options: validationOptions,
              constraints: [],
              validator: IsEmailUserAlreadyExistConstraint,
            });
          };
        }
    

    Then you need to import this class to the users module

    providers: [UsersService, IsEmailUserAlreadyExistConstraint]
    

    And after all, you can use this custom decorator in you DTO, where you can pass custom message as the error output

      @IsEmailUserAlreadyExist({
        message: 'Пользователь с таким email уже существует',
      })
      readonly email: string;