首页 > 解决方案 > 类验证器:使用类成员作为装饰器参数

问题描述

我有一个注册 DTO,其中一个成员依赖于另一个成员。

IsPostalCodeon需要知道countryCode zip/locale,它是其他类成员之一。

是否可以使用类成员作为装饰器参数?

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
}

标签: node.jstypescriptdecoratornestjsclass-validator

解决方案


您可以创建一个自定义验证器,如下所示:

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,
        ),
      },
    });
  };
}

用法:

export class SignupDto {
  @IsEmail()
  email: string

  @IsString()
  password: string

  @IsISO31661Alpha2()
  countryCode: string

  @IsPostalCodeOf('countryCode')
  zip: string
}

推荐阅读