node.jstypescriptdecoratornestjsclass-validator

Class validator: Use class member as decorator argument


I have a signup DTO where one member is dependent of another.

The IsPostalCode on zip needs to know the countryCode/locale, which is one of the other class members.

Is it possible to use a class member as decorator argument?

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
}

Solution

  • You can use the Validate decorator and create a custom validation method. For example, assuming you have properties zip and countryCode on your dto:

        @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}"`;
          }
        }
    

    Usage:

      @Validate(IsPostalCodeByCountryCode)
      public zip: string;