Skip to content

Access Root node in custom validation #1431

Open
@galwa

Description

@galwa

Inline with similar requests such as https://github.com/typestack/class-validator/pull/36
In cases where child/nested object requires a parent value for it's validation

I suggest adding root Object to validation function :

export interface ValidatorConstraintInterface {
    validate(value: any, validationArguments?: ValidationArguments, root ?: any): Promise<boolean> | boolean;
    defaultMessage?(validationArguments?: ValidationArguments): string;
}

It is a relatively simple change on ValidationExecutor that I do not identify and issues with

export class ValidationExecutor {
...
private root:any = undefined;
...
execute(object: object, targetSchema: string, validationErrors: ValidationError[]): void {
...
    if(this.root === undefined){
      this.root = object;
    }

private customValidations(object: object, value: any, metadatas: ValidationMetadata[], error: ValidationError): void {
...
    if (!metadata.each || !(Array.isArray(value) || value instanceof Set || value instanceof Map)) {
          const validatedValue = customConstraintMetadata.instance.validate(value, validationArguments,this.root);...
...
    const validatedSubValues = arrayValue.map((subValue: any) =>
          customConstraintMetadata.instance.validate(subValue, validationArguments,this.root)

From root object one can find any direct parent, as root contains the validate function ValidationArguments object

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