diff --git a/src/ForEach.ts b/src/ForEach.ts index a1ebfd2..af4790b 100644 --- a/src/ForEach.ts +++ b/src/ForEach.ts @@ -1,5 +1,5 @@ import { PropertyPath } from 'lodash'; -import { get, keys, isEmpty } from 'lodash/fp'; +import { get, keys, isEmpty, toPath } from 'lodash/fp'; import Context from './Context'; import Validator from './Validator'; @@ -47,8 +47,7 @@ class ForEach extends Validator { continue; } - const itemPath = [...collectionPath, key]; - const itemContext = context.applyPrefix(itemPath); + const itemContext = context.applyPrefix([...toPath(this.field), key]); nextErrors = this.validator.execute(values, nextErrors, itemContext); } diff --git a/tests/forEach.test.ts b/tests/forEach.test.ts index bba71fa..bde547c 100644 --- a/tests/forEach.test.ts +++ b/tests/forEach.test.ts @@ -41,3 +41,17 @@ test('forEach does handle lodash paths', () => { expect(schema.validate({ x: { y: [{}] } })).toEqual(expectedError); expect(schema.validate({ x: { y: [{ z: 'string' }] } })).toBeUndefined(); }); + +test('forEach properly resolve relative paths when nested multiple time', () => { + const schema = validators.compose( + validators.forEach('array', validators.forEach('subArray', validators.requiredString('field'))) + ); + + expect(schema.validate({ array: [] })).toBeUndefined(); + expect(schema.validate({ array: [{}] })).toBeUndefined(); + expect(schema.validate({ array: [{ subArray: [] }] })).toBeUndefined(); + expect(schema.validate({ array: [{ subArray: [{}] }] })).toEqual({ + array: [{ subArray: [{ field: defaultMessages.requiredValue }] }], + }); + expect(schema.validate({ array: [{ subArray: [{ field: 'string' }] }] })).toBeUndefined(); +});