Skip to content

Commit

Permalink
fix: only set fields to isBlurred after field blur or form submit
Browse files Browse the repository at this point in the history
  • Loading branch information
Pascalmh committed Sep 5, 2024
1 parent 64fefaa commit 45410e4
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 7 deletions.
8 changes: 1 addition & 7 deletions packages/form-core/src/FormApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -562,7 +562,7 @@ export class FormApi<
}

// If any fields are not blurred
if (!field.instance.state.meta.isBlurred) {
if (!field.instance.state.meta.isBlurred && cause === 'submit') {
// Mark them as blurred
field.instance.setMeta((prev) => ({ ...prev, isBlurred: true }))
}
Expand Down Expand Up @@ -629,12 +629,6 @@ export class FormApi<
fieldInstance.setMeta((prev) => ({ ...prev, isTouched: true }))
}

// If the field is not blurred (same logic as in validateAllFields)
if (!fieldInstance.state.meta.isBlurred) {
// Mark it as blurred
fieldInstance.setMeta((prev) => ({ ...prev, isBlurred: true }))
}

return fieldInstance.validate(cause)
}

Expand Down
22 changes: 22 additions & 0 deletions packages/form-core/tests/FieldApi.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,28 @@ describe('field api', () => {
expect(field.getValue()).toBe('other')
})

it('should set isBlurred correctly', () => {
const form = new FormApi({
defaultValues: {
names: ['test'],
},
})
form.mount()

const field = new FieldApi({
form,
name: 'names',
})
field.mount()

expect(field.getMeta().isBlurred).toBe(false)

field.pushValue('other')
field.validate('blur')

expect(field.getMeta().isBlurred).toBe(true)
})

it('should push an array value correctly', () => {
const form = new FormApi({
defaultValues: {
Expand Down
21 changes: 21 additions & 0 deletions packages/form-core/tests/FormApi.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1984,3 +1984,24 @@ describe('form api', () => {
expect(passconfirmField.state.meta.errors.length).toBe(0)
})
})

it('should update the onBlur state of the fields when the form is submitted', async () => {
const form = new FormApi({
defaultValues: {
firstName: '',
},
})

const field = new FieldApi({
form,
name: 'firstName',
})

field.mount()

expect(field.state.meta.isBlurred).toBe(false)

await form.handleSubmit()

expect(field.state.meta.isBlurred).toBe(true)
})

0 comments on commit 45410e4

Please sign in to comment.