【问题标题】:Two validators for one single entity in DTODTO 中一个实体的两个验证器
【发布时间】:2022-01-25 23:05:00
【问题描述】:

有没有办法或者是否可以在一个实体中拥有两个验证器?就像下面给出的示例代码一样,identifier 将接受电子邮件作为其有效负载,但它也将接受 号码/手机号码也作为其有效载荷。

  @ApiProperty()
  @IsString()
  @IsNotEmpty()
  @IsEmail()
  identifier: string;

编辑:

我试过了,

  @ApiProperty()
  @IsString()
  @IsNotEmpty()
  @IsEmail()
  @IsPhoneNumber('US')
  identifier: string;

但它不起作用。

编辑 2: 我根据之前的帖子找到了一个参考代码,How to use else condition in validationif decorator nestjs class-validator?,我复制了他的验证类。

import { ValidatorConstraint, ValidatorConstraintInterface, ValidationArguments } from "class-validator";
import { IdentifierType } from "../interface/access.interface";

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

        if (JSON.parse(JSON.stringify(args.object)).type === IdentifierType.MOBILE) {

            var regexp = new RegExp('/^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/im');
            // "regexp" variable now validate phone number.
            return regexp.test(identifier);
        } 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(identifier);
        }

    }

    defaultMessage(args: ValidationArguments) {

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

DTO -

export class VerifyOtpDto {
  @Validate(IdentifierValidation)
  @ApiProperty()
  @IsNotEmpty()
  identifier: string;

  @ApiProperty({ enum: IdentifierType })
  @IsNotEmpty()
  identifierType: IdentifierType;
}

枚举 -

export enum IdentifierType {
  EMAIL = 'email',
  MOBILE = 'mobile',
}

它确实适用于电子邮件,但尝试输入手机号码仍然不起作用。

【问题讨论】:

    标签: node.js typescript validation nestjs


    【解决方案1】:

    您有两种方法可以做到这一点,首先是使用正则表达式:

    @Matches(/YOUR_REGEX/, {message: 'identifier should be email or phone'})
    identifier: string;
    

    或者你可以从this得到想法:

    @IsType(Array<(val: any) => boolean>)
    @IsType([
     val => typeof val == 'string',
     val => typeof val == 'boolean',
    ])
    private readonly foo: boolean | string;
    

    【讨论】:

    • 嗨@Vahid,感谢您的意见!我已经更新了帖子。对当前自定义类验证的任何帮助都会非常有帮助。与此同时,我会看看你的建议。 ?
    【解决方案2】:

    当然它可以在一个 DTO 列中获得多个验证器。

    你检查https://www.npmjs.com/package/class-validator这里了吗?

    如果你想查看手机号码,可以使用@IsMobilePhone(locale: string)

    【讨论】:

    猜你喜欢
    • 2019-06-07
    • 1970-01-01
    • 2018-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多