0

I am using validateIf() to check if the paymentService is equal to some enum value defined in my code. But it does not validate and throws an error .


    @ApiProperty({ required: true })
    @IsNotEmpty()
    @IsEnum(PAYMENT_SERVICE,{
        message:`Payment Service must be one of the valid values ${Object.values(PAYMENT_SERVICE)}`
    })
    paymentService: PAYMENT_SERVICE
    
    @ApiProperty({ required: true })
    @IsNotEmpty()
    @IsInt()
    @Transform(({ value }) => parseInt(value))
    amount: number

    @ApiProperty({ required: false })
    @ValidateIf((object) => object.paymentService == PAYMENT_SERVICE.STRIPE)
    @IsString()
    @IsOptional()
    currency: string

    @ApiProperty({ required: true })
    @IsNotEmpty()
    @IsInt()
    @Transform(({ value }) => parseInt(value))
    qurandaziId: number
} 



export enum PAYMENT_SERVICE {
    STRIPE = 'STRIPE',
    JAZZCASH = 'JAZZCASH',
}


 

2 Answers 2

1

In currency field replace

@IsOptional()

with

@IsNotEmpty({ message: 'currency_not_empty' })
Sign up to request clarification or add additional context in comments.

Comments

1

It is important the order top-to-bottom of Validation Decorators. In this case, you place @IsOptional Validator below @ValidateIf. That means, after the .payment service has the value you need in the condition, you add the optional validator for the property currency.

In addition, a string, can be also an empty string, like "". So, it is not a good practice to have the currency as string. It 'd be better if you also defined another Enum for the various cases of currencies.

Below is an example of the code I 've used for production, which is the same case as yours.

  @ApiProperty({ description: 'Required for input currency.', required: false, enum: CurrencyEnum }) 
  @ValidateIf(obj => obj.action === InputEnum.CURRENCY)
  @IsEnum(CurrencyEnum)
  @IsNotEmpty({ message: 'currency must not be empty when input is "currency"' })
  currency!: CurrencyEnum;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.