Skip to content

Commit 251b253

Browse files
author
Larry Botha
committed
Merge branch 'master' into fix-invalid-modified-state-on-initialization
# Via GitHub (1) and Larry Botha (1) * master: fix(error initialisation): ensure array values in initialValues are represented in errors fix(error initialization): fix array values in schema validation being returned as strings test(async test): use 'done' callback to notify jest of test completion chore(package-lock.json): update style(various files): whitespace # Conflicts: # lib/create-form.js # lib/util.js # package-lock.json # test/library.spec.js
2 parents d8a3680 + 0930627 commit 251b253

File tree

4 files changed

+958
-460
lines changed

4 files changed

+958
-460
lines changed

lib/create-form.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ export const createForm = (config) => {
1919
values: () => util.cloneDeep(initialValues),
2020
errors: () =>
2121
validationSchema
22-
? util.getErrorsFromSchema(validationSchema.fields)
22+
? util.getErrorsFromSchema(initialValues, validationSchema.fields)
2323
: util.assignDeep(initialValues, NO_ERROR),
2424
touched: () => util.assignDeep(initialValues, !IS_TOUCHED),
2525
};

lib/util.js

Lines changed: 30 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -36,15 +36,37 @@ function getValues(object) {
3636
return result;
3737
}
3838

39-
function getErrorsFromSchema(schema, errors = {}) {
39+
// TODO: refactor this so as not to rely directly on yup's API
40+
// This should use dependency injection, with a default callback which may assume
41+
// yup as the validation schema
42+
function getErrorsFromSchema(initialValues, schema, errors = {}) {
4043
for (const key in schema) {
41-
if (schema[key].type === 'object' && !isEmpty(schema[key].fields)) {
42-
errors[key] = getErrorsFromSchema(
43-
schema[key].fields,
44-
Object.assign({}, errors),
45-
);
46-
} else {
47-
errors[key] = '';
44+
switch (true) {
45+
case schema[key].type === 'object' && !isEmpty(schema[key].fields): {
46+
errors[key] = getErrorsFromSchema(
47+
initialValues[key],
48+
schema[key].fields,
49+
Object.assign({}, errors[key]),
50+
);
51+
break;
52+
}
53+
54+
case schema[key].type === 'array': {
55+
const values =
56+
initialValues && initialValues[key] ? initialValues[key] : [];
57+
errors[key] = values.map((value) =>
58+
getErrorsFromSchema(
59+
value,
60+
schema[key].innerType.fields,
61+
Object.assign({}, errors[key]),
62+
),
63+
);
64+
break;
65+
}
66+
67+
default: {
68+
errors[key] = '';
69+
}
4870
}
4971
}
5072

0 commit comments

Comments
 (0)