Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: @ValidateNested() does not work with @Validate(CustomValidator) #2509

Open
pkvinhu opened this issue Jul 23, 2024 · 0 comments
Open

fix: @ValidateNested() does not work with @Validate(CustomValidator) #2509

pkvinhu opened this issue Jul 23, 2024 · 0 comments
Labels
status: needs triage Issues which needs to be reproduced to be verified report. type: fix Issues describing a broken feature.

Comments

@pkvinhu
Copy link

pkvinhu commented Jul 23, 2024

Description

When I use @ValidateNested() on its own (together with class-transformer @Type(() => class), works as expected, but when I try to use it with @Validate(CustomValidator), it seems to get skipped straight to the custom validator.

class SomeClass {
    @ApiProperty({ description: 'xyz', type: SomeObject })
    @IsNotEmpty()
    @ValidateNested()
    @Validate(SomeObjectValidator)
    @Type(() => SomeObject)
    someObject: SomeObject;
}

@ValidatorConstraint({ name: 'triggerValidator', async: false })
class SomeObjectValidator implements ValidatorConstraintInterface {
    private validationErrors: string[];

    public readonly attributesKeysMessage = `attribute keys message.`;

    validate(someObject: SomeObject): boolean {
        this.validationErrors = [];
        if (Object.keys(someObject.attributes).length !== 1) {
            this.validationErrors.push(this.attributesKeysMessage);
        }
        return this.validationErrors.length === 0;
    }

    defaultMessage(): string {
        return this.validationErrors[0] || 'Validation failed';
    }
}

class Trigger {
    @ApiProperty({ description: 'Type of some object' })
    @IsNotEmpty()
    type: string;

    @ApiProperty({ description: 'Attributes of some object' })
    @IsNotEmpty()
    attributes: Record<string, unknown>;
}

Expected behavior

When SomeObject is defined without attributes:

{
   type: 'hello world'
   // no attributes
}

it should return a validation error telling me attributes must not be empty, not running the custom validator at all

Actual behavior

The custom validator is run (skipping the @ValidateNested), returning an error Cannot convert undefined or null to object

@pkvinhu pkvinhu added status: needs triage Issues which needs to be reproduced to be verified report. type: fix Issues describing a broken feature. labels Jul 23, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
status: needs triage Issues which needs to be reproduced to be verified report. type: fix Issues describing a broken feature.
Development

No branches or pull requests

1 participant