cur*_*ets 6 decorator node.js typescript class-validator nestjs
我有一个注册 DTO,其中一名成员依赖于另一名成员。
需要IsPostalCode知道zip国家/地区代码/区域设置,它是其他类成员之一。
是否可以使用类成员作为装饰器参数?
import {
IsEmail,
IsISO31661Alpha2,
IsPostalCode,
IsString
} from "class-validator"
export class SignupDto {
@IsEmail()
email: string
@IsString()
password: string
@IsISO31661Alpha2()
countryCode: string
// Something like this
@IsPostalCode(this.countryCode)
zip: string
}
Run Code Online (Sandbox Code Playgroud)
您可以创建一个自定义验证器,如下所示:
import {
ValidationOptions,
registerDecorator,
ValidationArguments,
buildMessage,
} from 'class-validator';
/**
* Install validator package from npm. class-validator uses validator under the
* hood
*/
import {isISO31661Alpha2,isPostalCode} from 'validator';
export function IsPostalCodeOf(
property: string,
validationOptions?: ValidationOptions,
) {
// eslint-disable-next-line @typescript-eslint/ban-types
return function(object: Object, propertyName: string) {
registerDecorator({
name: 'isPostalCodeOf',
target: object.constructor,
propertyName: propertyName,
constraints: [property],
options: validationOptions,
validator: {
validate(value: any, args: ValidationArguments) {
// Getting the country code field from the argument.
// countryCode field from SignupDto
const [countryCodeField] = args.constraints;
// Getting the value of the countryCode Field
const countryCode = (args.object as any)[countryCodeField];
// Checking if the country code is valid even though it is checked
// at class level
if (!isISO31661Alpha2(countryCode)) {
// Invalid county code
return false;
}
// Checks if the value (zip) belongs in the extracted countryCode
// field
return isPostalCode(value,countryCode);
},
// Specifiy your error message here.
defaultMessage: buildMessage(
eachPrefix =>
`${eachPrefix} $property must be a valid postal
code in the specified country `,
validationOptions,
),
},
});
};
}
Run Code Online (Sandbox Code Playgroud)
用法:
export class SignupDto {
@IsEmail()
email: string
@IsString()
password: string
@IsISO31661Alpha2()
countryCode: string
@IsPostalCodeOf('countryCode')
zip: string
}
Run Code Online (Sandbox Code Playgroud)
您可以使用Validate装饰器并创建自定义验证方法。例如,假设您有属性zip并且countryCode在您的 dto 上:
@ValidatorConstraint({ name: 'isPostalCodeByCountryCode', async: false })
class IsPostalCodeByCountryCode implements ValidatorConstraintInterface {
validate(zip: string, args: ValidationArguments) {
// @ts-ignore
return isPostalCode(zip, args.object.countryCode);
}
defaultMessage(args: ValidationArguments) {
// @ts-ignore
return `Invalid zip "${args.object.zip}" for country "${args.object.countryCode}"`;
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
@Validate(IsPostalCodeByCountryCode)
public zip: string;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11901 次 |
| 最近记录: |