如何在 validationif decorator nestjs class-validator 中使用 else 条件?

How to use else condition in validationif decorator nestjs class-validator?

我需要有条件地验证在 nestjs class-validator 中提交的输入。有一个 validateif 装饰器,但如何在 else 部分添加另一个验证?例如:如果第一个输入是电子邮件,如果它 phone 匹配我的正则表达式,则使用电子邮件装饰器。

    @IsNotEmpty()
    @IsEnum(UsernameType)
    public type: UsernameType;

// enum has two value: phone and email

    @IsNotEmpty()
    @ValidateIf(o => o.type === UsernameType.PHONE )
    @Matches(/(09)[0-9]{9}/)
    username: number;

    @IsNotEmpty()
    @ValidateIf(o => o.type === UsernameType.EMAIL)
    @IsEmail()
    username: string;
    

我使用 class-validator 中提供的自定义验证 class 解决了这个问题。 基于: https://github.com/typestack/class-validator#custom-validation-classes.

Dto:


import { IsEmail, IsEnum, IsNotEmpty, Matches, Validate, ValidateIf } from "class-validator";
import { UsernameValidation } from "src/validations/username-validation";
import { UsernameType } from "../username-type.enum";

export class TypeDto {

    @IsNotEmpty()
    @IsEnum(UsernameType)
    public type: UsernameType;

    @Validate(UsernameValidation)
    @IsNotEmpty()
    username: string;
}

src/validations/username-validation:

import { TypeDto } from '../user/dto/type.dto';
import { UsernameType } from '../user/username-type.enum';
import { ValidatorConstraint, ValidatorConstraintInterface, ValidationArguments, Matches } from 'class-validator';

@ValidatorConstraint({ name: 'UsernameValidation', async: false })
export class UsernameValidation implements ValidatorConstraintInterface {
    validate(username: string, args: ValidationArguments) {

        if (JSON.parse(JSON.stringify(args.object)).type === UsernameType.PHONE) {


            var regexp = new RegExp('(09)[0-9]{9}');
            // "regexp" variable now validate iranian phone number.
            return regexp.test(username);
        } else {
            regexp = new RegExp("^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$");
            // "regexp" variable now validate email address.
            return regexp.test(username);
        }

    }

    defaultMessage(args: ValidationArguments) {

        if (JSON.parse(JSON.stringify(args.object)).type === UsernameType.PHONE) {
            return 'Enter a valid phone number.'
        } else {
            return 'Enter a valid email address.'
        }
    }
}