Skip to content

Commit e646980

Browse files
wowlusitongn1k0
authored andcommitted
Fix rjsf-team#223: Allow adding a custom validation error at a given array index (rjsf-team#521)
1 parent 0f9d1d2 commit e646980

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed

src/validate.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,14 @@ function createErrorHandler(formData) {
8888
handler
8989
);
9090
}
91+
if (Array.isArray(formData)) {
92+
return formData.reduce(
93+
(acc, value, key) => {
94+
return { ...acc, [key]: createErrorHandler(value) };
95+
},
96+
handler
97+
);
98+
}
9199
return handler;
92100
}
93101

test/validate_test.js

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -368,6 +368,62 @@ describe("Validation", () => {
368368
});
369369
});
370370

371+
it("should validate an array of object", () => {
372+
const schema = {
373+
type: "array",
374+
items: {
375+
type: "object",
376+
properties: {
377+
pass1: { type: "string" },
378+
pass2: { type: "string" },
379+
},
380+
},
381+
};
382+
383+
const formData = [
384+
{ pass1: "a", pass2: "b" },
385+
{ pass1: "a", pass2: "a" },
386+
];
387+
388+
function validate(formData, errors) {
389+
formData.forEach(({ pass1, pass2 }, i) => {
390+
if (pass1 !== pass2) {
391+
errors[i].pass2.addError("Passwords don't match");
392+
}
393+
});
394+
return errors;
395+
}
396+
397+
const { comp } = createFormComponent({
398+
schema,
399+
validate,
400+
liveValidate: true,
401+
});
402+
comp.componentWillReceiveProps({ formData });
403+
404+
expect(comp.state.errorSchema).eql({
405+
0: {
406+
pass1: {
407+
__errors: [],
408+
},
409+
pass2: {
410+
__errors: ["Passwords don't match"],
411+
},
412+
__errors: [],
413+
},
414+
1: {
415+
pass1: {
416+
__errors: [],
417+
},
418+
pass2: {
419+
__errors: [],
420+
},
421+
__errors: [],
422+
},
423+
__errors: [],
424+
});
425+
});
426+
371427
it("should validate a simple array", () => {
372428
const schema = {
373429
type: "array",
@@ -393,6 +449,9 @@ describe("Validation", () => {
393449
comp.componentWillReceiveProps({ formData });
394450

395451
expect(comp.state.errorSchema).eql({
452+
0: { __errors: [] },
453+
1: { __errors: [] },
454+
2: { __errors: [] },
396455
__errors: ["Forbidden value: bbb"],
397456
});
398457
});

0 commit comments

Comments
 (0)