Search code examples
nestjsdtoclass-validator

How to use class validator decorator optionally in Nest.js dto


I am using class validator in nest js validate the request data. In the request body I have a field called isEmailOrPhone. To validate email I need IsEmail decorator and to validate phone number I need IsPhoneNumber decorator in to validate them separetly.

But how can I validate a field where it can be both email or phone number? Is there any OR operation in class validator that gives true if any one of them is true?

Like: @IsEmaail() || @IsPhoneNumber()

Update:

I also created custom validator like following.

import { registerDecorator, ValidationOptions, ValidationArguments, IsEmail, IsPhoneNumber } from 'class-validator';

export function IsEmailOrPhone(validationOptions?: ValidationOptions) {
  return function (object: Object, propertyName: string) {
    registerDecorator({
      name: 'IsEmailOrPhone',
      target: object.constructor,
      propertyName: propertyName,
      options: validationOptions,
      validator: {
        validate(value: any, args: ValidationArguments) {
          const isEmailValid = IsEmail(value);
          const isPhoneValid = IsPhoneNumber(value);
      
          return isEmailValid || isPhoneValid;
          
        },
      },
    });
  };
}

The decorator IsEmail and IsPhoneNumber are returning data of type PropertyDecorator but the validate function needs to return either boolean or Promise<boolean>.

So how can I send boolean data?


Solution

  • If I recall correctly, you'll actually want to use isEmail and isPhone instead of IsEmail and IsPhone. From what I remember, the lowercase methods (is*) are the actual validation methods while the uppercase ones (Is*) are the decorators.