Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/salty-carpets-follow.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tanstack/form-core': patch
---

clear onSubmit error for fields without associated instance
17 changes: 17 additions & 0 deletions packages/form-core/src/FormApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1655,6 +1655,23 @@ export class FormApi<
if (!fieldInstance) {
const { hasErrored } = this.validateSync(cause)

// Clear stale onSubmit errors on this field when validation passes,
// mirroring what FieldApi.validateSync does for mounted fields.
if (!hasErrored && cause !== 'submit') {
const submitErrKey = getErrorMapKey('submit')
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (this.getFieldMeta(field)?.errorMap?.[submitErrKey]) {
this.setFieldMeta(field, (prev = defaultFieldMeta) => ({
...prev,
errorMap: { ...prev.errorMap, [submitErrKey]: undefined },
errorSourceMap: {
...prev.errorSourceMap,
[submitErrKey]: undefined,
},
}))
}
}

if (hasErrored && !this.options.asyncAlways) {
return this.getFieldMeta(field)?.errors ?? []
}
Expand Down
29 changes: 29 additions & 0 deletions packages/form-core/tests/FormApi.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2568,6 +2568,35 @@ describe('form api', () => {
expect(form.state.errors).toStrictEqual([])
})

it('should clear onSubmit field errors via setFieldValue without field instance mounted', async () => {
const validateMessage = 'first name is required'
const form = new FormApi({
defaultValues: { firstName: '' },
validators: {
onSubmit: ({ value }) => {
if (value.firstName.length === 0)
return { fields: { firstName: validateMessage } }
return null
},
},
})

form.mount()

await form.handleSubmit()
expect(form.state.isFieldsValid).toBe(false)
expect(form.state.canSubmit).toBe(false)
expect(form.state.fieldMeta.firstName?.errorMap.onSubmit).toBe(
validateMessage,
)

form.setFieldValue('firstName', 'John')

expect(form.state.fieldMeta.firstName?.errorMap.onSubmit).toBeUndefined()
expect(form.state.isFieldsValid).toBe(true)
expect(form.state.canSubmit).toBe(true)
})

it('should run validators in order form sync -> field sync -> form async -> field async', async () => {
const order: string[] = []
const formAsyncChange = vi.fn().mockImplementation(async () => {
Expand Down