node.jsnestjsclass-validator

how to make sure at least one field is not empty?(its ok if only one is not empty)


I'm writing a registration endpoint for an api i'm working on and i'm using nestjs and class-validator to validate the input data. The user can register using either their phone number or email address or both. So to validate the input, I should make sure that at least one of them is provided. But I'm having a hard time figuring out how to do it without making a mess.

This is my dto:

export class register {
  @ApiModelProperty()
  @IsNotEmpty()
  @IsAlpha()
  firstName: string

  @ApiModelProperty()
  @IsNotEmpty()
  @IsAlpha()
  lastName: string

  @ApiModelProperty()
  @ValidateIf(o => o.email == undefined)
  @IsNotEmpty()
  @isIRMobile()
  phone: string

  @ApiModelProperty()
  @ValidateIf(o => o.phone == undefined)
  @IsNotEmpty()
  @IsEmail()
  email: string

  @ApiModelProperty()
  @IsNotEmpty()
  password: string
}

As you can see, i've used conditional validation which works for the cases that only one of phone number or email address is provided. But the problem is that when both are provided, one of them won't be validated and an invalid value will be allowed.

Any suggestions?


Solution

  • I made a simpler solution, the whole idea of "AnyOf" is to invoke @ValidateIf() on properties. But in order this to be done in a clean way, you have to use Descriptors, here is my solution:

    export function AnyOf(properties: string[]) {
      return function (target: any) {
        for (const property of properties) {
          const otherProps = properties.filter(prop => prop !== property);
          const decorators = [
            // Validates if all other properties are undefined.
            ValidateIf((obj: any) =>
              obj[property] !== undefined || otherProps.reduce(
                (acc, prop) => acc && obj[prop] === undefined,
                true,
              ),
            ),
          ];
    
          for (const decorator of decorators) {
            applyDecorators(decorator)(target.prototype, property);
          }
        }
      };
    }
    
    @AnyOf(['email', 'phone'])
    class CreateUserDto {
      @IsString()
      email: string
    
      @IsString()
      phone: string
    }