Skip to content

feature: Conditional validation inside validation optionsΒ #1721

@soroushmadani

Description

@soroushmadani

Description

Sometimes we need to validate a field based on another field in the dto.

Proposed solution

  1. it would be nice to have an option called validateIf which is a callback function with given object.
    example:
export class TestDto {
 // ...

 @IsNotEmpty()
 @IsString()
 type: string;

 @IsUUID({ validateIf: o => o.type === "something" })
 @IsEmpty({ validateIf: o => o.type === "something" })
 @IsNotEmpty({ validateIf: o => o.type !== "something" })
 albumId: string;
}
  1. the above example would do the job for me, but it would be nicer if we could group validation somehow like below:
export class TestDto {
// ...

 @ValidationGroup([IsUUID(), IsEmpty()], { validateIf: o => o.type === "something" })
 @IsNotEmpty({ validateIf: o => o.type !== "something" })
 albumId: string;
}

or:

export class TestDto {
// ...

 @ValidationGroup(o => {
   if (o.type === "something" ) {
     return [IsUUID(), IsEmpty()]
   }
   return [IsNotEmpty()]
 })
 albumId: string;
}

In general, it's really good to access current object when validating. for example I needed to set the max value of a number based on another field. I made my own decorator which works like:

 @Max((o) =>
    o.type === DiscountPlanType.Percentage ||
      ? 100
      : false, // when false is passed, this will be skipped
  )

Metadata

Metadata

Assignees

No one assigned

    Labels

    flag: needs discussionIssues which needs discussion before implementation.type: featureIssues related to new features.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions