Skip to content

How to validate a property is optional only if another property is defined? #395

@shafi-

Description

@shafi-

Is there an existing issue that is already proposing this?

  • I have searched the existing issues

Is your feature request related to a problem? Please describe it

Disclaimer: This is probably not an existing problem.

Recently there was a requirement to make a property optional when another property is defined.

Is there any specific approach or combination of existing validators to achieve that?

Describe the solution you'd like

There could be a validator IsOptionalWhenDefined('depenedencyProp').

So if dependencyProp is defined, the validations should consider the prop as optional similar to IsOptional. Otherwise, it should be required and other validations should not be ignored.

Teachability, documentation, adoption, migration strategy

So the usage can be like:

class Test {
     propA: string;

     @IsOptionalWhenDefined('propA')
     propB?: string;
}

What is the motivation / use case for changing the behavior?

Recently there was a requirement to make a property optional when another property is defined.

We had to validate an api request body where the requirement is a property is optional if another property exists.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions