Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 794
massivefermion Avatar asked Jun 30 '19 17:06

massivefermion


1 Answers

I think you just need to add

@ValidateIf(o => o.email == undefined || o.phone)
phone: string

and

@ValidateIf(o => o.phone == undefined || o.email)
email: string

EDITED

A small addition

I'd suggest validating like this:

@ValidateIf(o => !o.email || o.phone)
phone: string

@ValidateIf(o => !o.phone || o.email)
email: string

to properly handle null, 0 and "" (empty string)

otherwise, this will be correct as well (it shouldn't be):

const data = new register();
data.phone = '';
data.email = '';
like image 118
Andrei Kamenskikh Avatar answered Nov 06 '22 06:11

Andrei Kamenskikh