class-validator icon indicating copy to clipboard operation
class-validator copied to clipboard

An "or" decorator! so that a property can be of multiple types

Open joseDaKing opened this issue 3 years ago • 2 comments

Description

It is nice to have an "or" decorator so an property can be of multiple types. For example a sign-in request in a REST api can have 2 properties, a password property that is of type alphanumeric and user a property of either alphanumeric thereby a username or email type.

Proposed solution

class SignInDto {
    @Or([
        IsAlphanumeric(),
        IsEmail()
    ])
    user: string;
 
    @IsAlphanumeric()
    password: string;
}

An alternative solution is to have sign-in request consist of 3 properties instead of 2 properties. The 3 properties are a username property that should be of alphanumeric type and also optional, email property that should be of email type and also optional, lastly password property of alphanumeric type.

class SignInDto {

    @IsOptional()
    @IsAlpahnumeric()
    username: string;

    @IsOptional()
    @IsEmail()
    email: string;

    @IsAlphanumeric()
    password: string;
}

This solution is flawed because the end user that uses the REST api can send a sign-in request where both username and email are defined but not related and that can lead to problems. To prevent it you should check that if username property is defined than the email cannot be defined or vice versa. That makes the code verbose.

joseDaKing avatar Aug 21 '20 13:08 joseDaKing