0

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

1
  • Can you show what you're doing to make the server return a 500? Commented May 11, 2022 at 1:13

1 Answer 1

5

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;
Sign up to request clarification or add additional context in comments.

6 Comments

Thank you, this should help, but could you explain the syntax a little. it'll go a long way helping in creating mine when i want to change the functionality.
Sure, first of all you need to create a class IsEmailUserAlreadyExistConstraint, decorate it with ValidatorConstraint and it must implement interface ValidatorConstraintInterface. By implementing this interface you expose method validate which takes some value from your DTO as string and must return true or false. That is the basic logic of class validator.
Next, you need to decorate this class using Injectable decorator. It allows you to inject service or repository to the class constructor
After, creating function IsEmailUserAlreadyExist just creates new decorator for code simplicity and possibility to use our class validation using one decorator
Thanks for all your help man, could you share a social media profile so that we can connect?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.