Skip to content

Commit

Permalink
fix: errors not resetting once values are correct
Browse files Browse the repository at this point in the history
  • Loading branch information
Keaton Roux committed Dec 18, 2024
1 parent d178f33 commit ee9a7e6
Show file tree
Hide file tree
Showing 2 changed files with 87 additions and 0 deletions.
41 changes: 41 additions & 0 deletions packages/form-core/src/FormApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -747,6 +747,26 @@ export class FormApi<
}))
}
}
} else {
for (const [field] of Object.entries(this.fieldInfo)) {
this.setFieldMeta(field as DeepKeys<TFormData>, (prev) => {
const newErrorMap = prev.errorMap;

if (prev.isDirty) {
for (const [errorKey] of Object.entries(prev.errorMap)) {
newErrorMap[errorKey as ValidationErrorMapKeys] = undefined
}
}

return {
...prev,
errorMap: {
...prev.errorMap,
[errorMapKey]: undefined,
},
}
})
}
}

if (this.state.errorMap[errorMapKey] !== formError) {
Expand Down Expand Up @@ -875,7 +895,28 @@ export class FormApi<
}))
}
}
} else {
for (const [field] of Object.entries(this.fieldInfo)) {
this.setFieldMeta(field as DeepKeys<TFormData>, (prev) => {
const newErrorMap = prev.errorMap;

if (prev.isDirty) {
for (const [errorKey] of Object.entries(prev.errorMap)) {
newErrorMap[errorKey as ValidationErrorMapKeys] = undefined
}
}

return {
...prev,
errorMap: {
...prev.errorMap,
[errorMapKey]: undefined,
},
}
})
}
}

this.store.setState((prev) => ({
...prev,
errorMap: {
Expand Down
46 changes: 46 additions & 0 deletions packages/zod-form-adapter/tests/FormApi.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -184,4 +184,50 @@ describe('zod form api', () => {
name0Field.setValue('qwer')
expect(name0Field.getMeta().errors).toEqual([])
})

it('should clear errors if previously errors were set and now are fixed', () => {
const form = new FormApi({
defaultValues: {
password: '',
confirmPassword: '',
},
validatorAdapter: zodValidator(),
validators: {
onChange: z.object({
password: z.string(),
confirmPassword: z.string(),
}).refine(({ password, confirmPassword }) => password === confirmPassword, {
message: 'Passwords must match',
path: ['password'],
})
}
});
form.mount();

const field1 = new FieldApi({
form,
name: 'password',
defaultMeta: {
isTouched: true,
},
});
field1.mount();

const field2 = new FieldApi({
form,
name: 'confirmPassword',
defaultMeta: {
isTouched: true,
},
});
field2.mount();

field1.setValue('password');
expect(field1.getMeta().errors).toStrictEqual(['Passwords must match']);
expect(form.state.canSubmit).toBe(false);

field2.setValue('password');
expect(field2.getMeta().errors).toStrictEqual([]);
expect(form.state.canSubmit).toBe(true);
})
})

0 comments on commit ee9a7e6

Please sign in to comment.