Skip to content

Commit

Permalink
fix: solve path resolution when nesting forEach validators
Browse files Browse the repository at this point in the history
  • Loading branch information
amille44420 committed Oct 21, 2022
1 parent a659300 commit 115faa1
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 3 deletions.
5 changes: 2 additions & 3 deletions src/ForEach.ts
Original file line number Diff line number Diff line change
@@ -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';

Expand Down Expand Up @@ -47,8 +47,7 @@ class ForEach<TOuterContext = any> extends Validator<TOuterContext> {
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);
}
Expand Down
14 changes: 14 additions & 0 deletions tests/forEach.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
});

0 comments on commit 115faa1

Please sign in to comment.