有沒有辦法或者是否可以在一個物體中擁有兩個驗證器?就像下面給出的示例代碼一樣,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',
}
它確實適用于電子郵件,但嘗試提供手機號碼仍然不起作用。
uj5u.com熱心網友回復:
您有兩種方法可以做到這一點,首先使用正則運算式:
@Matches(/YOUR_REGEX/, {message: 'identifier should be email or phone'})
identifier: string;
或者你可以從中得到這個想法:
@IsType(Array<(val: any) => boolean>)
@IsType([
val => typeof val == 'string',
val => typeof val == 'boolean',
])
private readonly foo: boolean | string;
uj5u.com熱心網友回復:
當然,它可以在一個 DTO 列中獲得多個驗證器。
你在這里檢查https://www.npmjs.com/package/class-validator了嗎?
如果要查看手機號碼,可以使用 to @IsMobilePhone(locale: string)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/422895.html
標籤:
上一篇:使用COPY命令將資料從AmazonS3加載到redshift復制行而不是覆寫行資料
下一篇:筆記:linux 總結
