Repository navigation
Closed
Labels
flag: BREAKING CHANGEIssues containing a breaking change, requiring a major release.status: done/releasedIssue has been completed, no further action is needed.type: fixIssues describing a broken feature.
Description
Description
When a property has a @ValidateNested() decorator and the validated data on the property is not an object or array the validation error incorrectly assigned to the children instead of the parent.
Minimal code-snippet showcasing the problem
import 'reflect-metadata';
import { validateSync, IsString, ValidateNested } from 'class-validator';
class SubClass {
@IsString()
name: string;
}
class ExampleClass {
@ValidateNested()
nestedWithClassValue: SubClass;
@ValidateNested()
nestedWithPrimitiveValue: SubClass;
}
const instance = new ExampleClass ();
instance.nestedWithClassValue = new SubClass();
instance.nestedWithPrimitiveValue = "invalid" as any;
const validationErrors = validateSync(instance);Expected behavior
I have expected the error for the nestedWithPrimitiveValue property to appear on the root object instead of children.
[
{
"target": {
"nestedWithClassValue": {},
"nestedWithPrimitiveValue": "invalid"
},
"value": {},
"property": "nestedWithClassValue",
"children": [
{
"target": {},
"property": "name",
"children": [],
"constraints": {
"isString": "name must be a string"
}
}
]
},
{
"target": {
"nestedWithClassValue": {},
"nestedWithPrimitiveValue": "invalid"
},
"value": "invalid",
"property": "nestedWithPrimitiveValue",
"constraints": {
"nestedValidation": "nested property nestedWithPrimitiveValue must be either object or array"
}
}
]Actual behavior
Currently the validationErrors will be the following structure:
[
{
"target": {
"nestedWithClassValue": {},
"nestedWithPrimitiveValue": "invalid"
},
"value": {},
"property": "nestedWithClassValue",
"children": [
{
"target": {},
"property": "name",
"children": [],
"constraints": {
"isString": "name must be a string"
}
}
]
},
{
"target": {
"nestedWithClassValue": {},
"nestedWithPrimitiveValue": "invalid"
},
"value": "invalid",
"property": "nestedWithPrimitiveValue",
"children": [
{
"value": "invalid",
"property": "nestedWithPrimitiveValue",
"constraints": {
"nestedValidation": "nested property nestedWithPrimitiveValue must be either object or array"
}
}
]
}
]Observe how the nestedValidation constraint is applied to the children instead of the root object.
Reacted by zanminkian
Metadata
Metadata
Assignees
Labels
flag: BREAKING CHANGEIssues containing a breaking change, requiring a major release.status: done/releasedIssue has been completed, no further action is needed.type: fixIssues describing a broken feature.
Activity
github-actions commentedon Jan 10, 2023
This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.