Skip to content

Commit 0930627

Browse files
Merge pull request #80 from tjinauyeung/fix-validation-schema-array-values
fix(arrays in validation schema): ensure initialised $errors matches shape of initialValues
2 parents 364e23a + d21d08b commit 0930627

File tree

5 files changed

+21440
-86
lines changed

5 files changed

+21440
-86
lines changed

lib/create-form.js

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,10 @@ export const createForm = (config) => {
1717

1818
const getInitial = {
1919
values: () => util.cloneDeep(initialValues),
20-
errors: () => validationSchema ? util.getErrorsFromSchema(validationSchema.fields) : util.assignDeep(initialValues, NO_ERROR),
20+
errors: () =>
21+
validationSchema
22+
? util.getErrorsFromSchema(initialValues, validationSchema.fields)
23+
: util.assignDeep(initialValues, NO_ERROR),
2124
touched: () => util.assignDeep(initialValues, !IS_TOUCHED),
2225
};
2326

@@ -136,8 +139,8 @@ export const createForm = (config) => {
136139
if (yupErrors && yupErrors.inner) {
137140
const updatedErrors = getInitial.errors();
138141

139-
yupErrors.inner.forEach(error =>
140-
util.set(updatedErrors, error.path, error.message)
142+
yupErrors.inner.forEach((error) =>
143+
util.set(updatedErrors, error.path, error.message),
141144
);
142145

143146
errors.set(updatedErrors);

lib/util.js

Lines changed: 29 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -35,14 +35,37 @@ function getValues(object) {
3535
return result;
3636
}
3737

38-
function getErrorsFromSchema(schema, errors = {}) {
38+
// TODO: refactor this so as not to rely directly on yup's API
39+
// This should use dependency injection, with a default callback which may assume
40+
// yup as the validation schema
41+
function getErrorsFromSchema(initialValues, schema, errors = {}) {
3942
for (const key in schema) {
40-
if(schema[key].type === 'object' && !isEmpty(schema[key].fields)) {
41-
errors[key] = getErrorsFromSchema(schema[key].fields, Object.assign({}, errors));
42-
}
43+
switch (true) {
44+
case schema[key].type === 'object' && !isEmpty(schema[key].fields): {
45+
errors[key] = getErrorsFromSchema(
46+
initialValues[key],
47+
schema[key].fields,
48+
Object.assign({}, errors[key]),
49+
);
50+
break;
51+
}
4352

44-
else {
45-
errors[key] = '';
53+
case schema[key].type === 'array': {
54+
const values =
55+
initialValues && initialValues[key] ? initialValues[key] : [];
56+
errors[key] = values.map((value) =>
57+
getErrorsFromSchema(
58+
value,
59+
schema[key].innerType.fields,
60+
Object.assign({}, errors[key]),
61+
),
62+
);
63+
break;
64+
}
65+
66+
default: {
67+
errors[key] = '';
68+
}
4669
}
4770
}
4871

0 commit comments

Comments
 (0)