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?
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 = '';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With