Skip to content

Commit c80a7d9

Browse files
committed
Allow object validation
1 parent 87bc8cb commit c80a7d9

File tree

2 files changed

+20
-5
lines changed

2 files changed

+20
-5
lines changed

src/index.js

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,9 @@ const cleanKey = (str) => {
77
return parts[parts.length - 1];
88
}
99

10-
const flattenObject = (obj, prefix = '') => {
10+
/* template is because we don't want to flatten the data object if we're validating an object, otherwise we'll
11+
dig into the object to find the values to validate */
12+
const flattenObject = (obj, prefix = '', template = []) => {
1113
if (!obj) {
1214
return {};
1315
}
@@ -16,7 +18,9 @@ const flattenObject = (obj, prefix = '') => {
1618
typeof value === 'object' && !Array.isArray(value)
1719
? {
1820
...flattened,
19-
...flattenObject(value, `${prefix}${key}.`)
21+
...(template.includes(`${prefix}${key}`)
22+
? { [`${prefix}${key}`]: value }
23+
: flattenObject(value, `${prefix}${key}.`)),
2024
}
2125
: Object.assign(flattened, { [`${prefix}${key}`]: value }),
2226
{}
@@ -104,9 +108,8 @@ class Validator {
104108
}
105109

106110
async validate (data, rules) {
107-
const flatData = flattenObject(data);
108111
const flatRules = flattenObject(rules);
109-
112+
const flatData = flattenObject(data, undefined, Object.keys(flatRules));
110113
const validationResults = await Promise.all(
111114
Object.keys(flatRules).flatMap(
112115
async (key) => {

src/index.test.js

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -179,7 +179,19 @@ describe('integration tests', () => {
179179
expect(result.errorCount).toBe(2);
180180
});
181181

182-
test('should validate objects', async () => {
182+
183+
test('should validate objects when valid', async () => {
184+
const data = {
185+
field1: {},
186+
};
187+
const rules = {
188+
field1: 'required',
189+
}
190+
const result = await validator.validate(data, rules);
191+
expect(result.errors.field1).toHaveLength(0);
192+
});
193+
194+
test('should validate objects when invalid', async () => {
183195
const data = {
184196
field1: null,
185197
};

0 commit comments

Comments
 (0)