Skip to content

Commit

Permalink
fix(form-core): shift errors when inserting a value into an array
Browse files Browse the repository at this point in the history
  • Loading branch information
Balastrong committed Feb 6, 2025
1 parent 136a584 commit 52ef4e9
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/form-core/src/FormApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1278,6 +1278,7 @@ export class FormApi<

// Validate the whole array + all fields that have shifted
await this.validateField(field, 'change')
await this.validateArrayFieldsStartingFrom(field, index, 'change')
}

/**
Expand Down
66 changes: 66 additions & 0 deletions packages/form-core/tests/FormApi.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,72 @@ describe('form api', () => {
expect(form.state.errors).toStrictEqual(['At least 3 names are required'])
})

it("should shift errors when inserting an array field's primitive value", async () => {
const form = new FormApi({
defaultValues: {
names: ['one', 'two'],
},
})
form.mount()
// Since validation runs through the field, a field must be mounted for that array
new FieldApi({ form, name: 'names' }).mount()

const field0 = new FieldApi({
form,
name: 'names[0]',
validators: {
onChange: ({ value }) => value !== 'test' && 'Invalid value',
},
})
field0.mount()

const field1 = new FieldApi({
form,
name: 'names[1]',
validators: {
onChange: ({ value }) => value !== 'test' && 'Invalid value',
},
})
field1.mount()

expect(field0.state.meta.errors).toStrictEqual([])

field0.handleChange('other')
expect(field0.state.meta.errors).toStrictEqual(['Invalid value'])

await form.insertFieldValue('names', 0, 'test')

expect(field0.state.meta.errors).toStrictEqual([])
expect(field1.state.meta.errors).toStrictEqual(['Invalid value'])
})

it("should shift errors when inserting an array field's nested value", async () => {
const form = new FormApi({
defaultValues: {
names: [{ first: 'test' }, { first: 'test2' }],
},
})
form.mount()
// Since validation runs through the field, a field must be mounted for that array
new FieldApi({ form, name: 'names' }).mount()

const field1 = new FieldApi({
form,
name: 'names[0].first',
defaultValue: 'test',
validators: {
onChange: ({ value }) => value !== 'test' && 'Invalid value',
},
})
field1.mount()

expect(field1.state.meta.errors).toStrictEqual([])

await form.insertFieldValue('names', 0, { first: 'other' })

expect(field1.state.meta.errors).toStrictEqual(['Invalid value'])
})

it("should validate all shifted fields when inserting an array field's value", async () => {
const form = new FormApi({
defaultValues: {
Expand Down

0 comments on commit 52ef4e9

Please sign in to comment.