Skip to content

Commit 7f2453b

Browse files
authored
fix(form-core): Validate fields without instances (#2001)
1 parent a7eda7a commit 7f2453b

File tree

3 files changed

+42
-1
lines changed

3 files changed

+42
-1
lines changed

.changeset/happy-pillows-hear.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@tanstack/form-core': patch
3+
---
4+
5+
run validation for fields without instances

packages/form-core/src/FormApi.ts

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1599,7 +1599,18 @@ export class FormApi<
15991599
) => {
16001600
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
16011601
const fieldInstance = this.fieldInfo[field]?.instance
1602-
if (!fieldInstance) return []
1602+
1603+
if (!fieldInstance) {
1604+
const { hasErrored } = this.validateSync(cause)
1605+
1606+
if (hasErrored && !this.options.asyncAlways) {
1607+
return this.getFieldMeta(field)?.errors ?? []
1608+
}
1609+
1610+
return this.validateAsync(cause).then(() => {
1611+
return this.getFieldMeta(field)?.errors ?? []
1612+
})
1613+
}
16031614

16041615
// If the field is not touched (same logic as in validateAllFields)
16051616
if (!fieldInstance.state.meta.isTouched) {

packages/form-core/tests/standardSchemaValidator.spec.ts

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,31 @@ describe('standard schema validator', () => {
108108
])
109109
})
110110

111+
it('should handle form-level field errors for fields without a mounted FieldApi instance', () => {
112+
const form = new FormApi({
113+
defaultValues: {
114+
email: '',
115+
},
116+
validators: {
117+
onChange: z.object({
118+
email: z.string().email('email must be an email address'),
119+
}),
120+
},
121+
})
122+
123+
form.mount()
124+
125+
form.setFieldValue('email', 'not-an-email')
126+
127+
expect(form.state.errors).toMatchObject([
128+
{ email: [{ message: 'email must be an email address' }] },
129+
])
130+
131+
form.setFieldValue('email', '[email protected]')
132+
133+
expect(form.state.errors).toEqual([])
134+
})
135+
111136
it('should support standard schema async validation with zod', async () => {
112137
vi.useFakeTimers()
113138

0 commit comments

Comments
 (0)