类验证器:使用类成员作为装饰器参数

问题描述 投票:0回答:3

我有一个注册 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
}
node.js typescript decorator nestjs class-validator
3个回答
9
投票

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

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
}

4
投票

您可以使用

Validate
装饰器并创建自定义验证方法。例如,假设您的 dto 上有属性
zip
countryCode

    @ValidatorConstraint({ name: 'isPostalCodeByCountryCode', async: false })
    class IsPostalCodeByCountryCode implements ValidatorConstraintInterface {
      validate(zip: string, args: ValidationArguments): boolean {
        return isPostalCode(zip, (args.object as any).countryCode);
      }
    
      defaultMessage(args: ValidationArguments): string {
        return `Invalid zip "${(args.object as any).zip}" for country "${(args.object as any).countryCode}"`;
      }
    }

用途:

  @Validate(IsPostalCodeByCountryCode)
  public zip: string;

-3
投票

由于装饰器在打字稿中的工作方式,装饰器本身无法在其中使用类属性。您可以创建一个自定义验证装饰器来读取类的其他属性并正确验证 zip 属性,但这可能需要一些工作。

所以回答你的问题:

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

不,不是。

© www.soinside.com 2019 - 2024. All rights reserved.