Question3r
Question3r

Reputation: 3802

make field optional but let it depend on other fields if set

I have a DTO filtering locations. To query just some locations I can provide a latitude, longitude and radius. All three of them are optional fields but when I set one of them it requires the other two too. So what I have so far

export class GetLocationsDTO {
    @IsNumber()
    @IsLatitude()
    // optional but requires longitude and radius
    @Type(() => Number)
    public latitude?: number;

    @IsNumber()
    @IsLongitude()
    // optional but requires latitude and radius
    @Type(() => Number)
    public longitude?: number;

    @IsNumber()
    // optional but requires latitude and longitude
    @Type(() => Number)
    public radiusInKilometers?: number;
}

Is there a decorator like this sample

@IsOptionalButDependsOn(['fieldFoo', 'fieldBar'])

So all three of them are optional but if one of them was provided the other two fields have to be provided too.

Upvotes: 1

Views: 1182

Answers (1)

satanTime
satanTime

Reputation: 13574

I guess you need to add ValidateIf.

export class GetLocationsDTO {
    @IsNumber()
    @IsLatitude()
    @ValidateIf(o => o.radiusInKilometers !== undefined || o.longitude !== undefined)
    @Type(() => Number)
    public latitude?: number;

    @IsNumber()
    @IsLongitude()
    @ValidateIf(o => o.latitude !== undefined || o.radiusInKilometers !== undefined)
    @Type(() => Number)
    public longitude?: number;

    @IsNumber()
    @ValidateIf(o => o.latitude !== undefined || o.longitude !== undefined)
    @Type(() => Number)
    public radiusInKilometers?: number;
}

Upvotes: 3

Related Questions