feature: does not allow to send two different parameter at the same time.

Author: kasir-baratiCreated Mar 14, 2022Updated May 12, 2026
Labelstype: featureflag: needs discussion

Description

I am always struggling with validating in two places, I mean if I have to do something like this in my validator layer with class-validator:

typescript
export class TestDto {
    @IsOptional()
    @ValidateIf(obj => !obj.propertyB)
    @IsString()
    @IsNotEmpty()
    propertyA: string;

    @IsOptional()
    @ValidateIf(obj => !obj.propertyA)
    @IsString()
    @IsNotEmpty()
    propertyB: string;
}

And in the controller I have to do this too:

typescript
if (createDto.propertyA && createDto.propertyB) {
    throw new BadRequestException('Please speciffy propertyA or propertyB, not both of them at the same time');
}

Proposed solution

I like to had another decorator to decorate my class-validator with it to tell class-validator you should allow request to passed away if in the request body we have only one of the propertyA or propertyB. Something like this:

typescript
@RejectWhenThesePropertiesWereInTheRequest(["propertyA", "propertyB"], {
    message: 'Please speciffy propertyA or propertyB, not both of them at the same time'
})
export class TestDto {
    @IsOptional()
    @ValidateIf(obj => !obj.propertyB)
    @IsString()
    @IsNotEmpty()
    propertyA: string;

    @IsOptional()
    @ValidateIf(obj => !obj.propertyA)
    @IsString()
    @IsNotEmpty()
    propertyB: string;
}

I am not sure is it possible or not I just thought this feature would be a cool one. As you can see there is questions about it too in stackoverflow: question 1, and question 2

Source: typestack/class-validator