class-validator icon indicating copy to clipboard operation
class-validator copied to clipboard

question: Alternative to ValidateIf due to Security breach

Open DarioVisiert opened this issue 8 months ago • 1 comments

I was trying to make a form builder validation for backend service. In this i have data occur dependant on the user choice. As Further input depends on previous choices i have conditional fields that need to be present e.g.

{ vehicleType: "truck" | "car" carData?: "car Specific Props" truckdata?: "TruckSpecific Props" }

The problem:

With ValidateIf i could check that the either carData or truckData is present based on vehicleData. But it still leaves me with the security breach that teh other one is not type checked at and therefore prune to inject any data in the json.

e.g.

{ vehicleType: "truck", truckData: "TruckData" carData: "Mailicious Json" ❌ }

Is there any clean and secure solution to this problem with class-validator?

DarioVisiert avatar May 11 '25 20:05 DarioVisiert

Up!

I'm using a custom decorator in my nestjs application, but I wonder if there's some other way to deal with it. This is my decorator:

import { applyDecorators } from '@nestjs/common';
import { ValidateIf, ValidationOptions } from 'class-validator';
import { Transform } from 'class-transformer';

/**
* Makes the field `undefined` unless the given condition returns true.
 */
export function OptionalIf<T>(
  condition: (object: T) => boolean,
  validationOptions?: ValidationOptions,
): PropertyDecorator {
  return applyDecorators(
    Transform(({ obj, value }: { obj: T; value: unknown }) =>
      condition(obj) ? value : undefined,
    ),
    ValidateIf(condition, validationOptions),
  );
}

CiroGomes avatar Jun 11 '25 03:06 CiroGomes