Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] Fix bug with incorrect errors for nested fields #271

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
47 changes: 47 additions & 0 deletions src/FinalForm.validating.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -818,6 +818,53 @@ describe('Field.validation', () => {
expect(firstName1.mock.calls[0][0].error).toBe('Required')
})

it('should handle nested field-level errors correctly', () => {
const form = createForm({ onSubmit: onSubmitMock })
const range = jest.fn()
const min = jest.fn()
const max = jest.fn()
const validate = jest.fn(value =>
value && value.max < value.min ? 'Invalid range' : undefined
)
const spy = jest.fn()
form.subscribe(spy, { errors: true })
form.registerField(
'range',
range,
{ error: true },
{
getValidator: () => validate
}
)
form.registerField('range.min', min, { error: true })
form.registerField('range.max', max, { error: true })
expect(validate).toHaveBeenCalledTimes(1)
expect(validate.mock.calls[0][0]).toBeUndefined()
expect(range).toHaveBeenCalledTimes(1)
expect(range.mock.calls[0][0].error).toBeUndefined()
expect(spy).toHaveBeenCalledTimes(1)
expect(spy.mock.calls[0][0].errors).toEqual({})

// add an empty customer
form.change('range.min', 10)

expect(validate).toHaveBeenCalledTimes(2)
expect(validate.mock.calls[1][0]).toEqual({ min: 10 })
expect(range).toHaveBeenCalledTimes(1)
expect(spy).toHaveBeenCalledTimes(1)

form.change('range.max', 5)

expect(validate).toHaveBeenCalledTimes(3)
expect(validate.mock.calls[2][0]).toEqual({ min: 10, max: 5 })
expect(range).toHaveBeenCalledTimes(2)
expect(range.mock.calls[1][0].error).toEqual('Invalid range')
expect(spy).toHaveBeenCalledTimes(2)
expect(spy.mock.calls[1][0].errors).toEqual({
range: 'Invalid range'
})
})

it('should only validate changed field when validateFields is empty', () => {
const form = createForm({ onSubmit: onSubmitMock })
const foo = jest.fn()
Expand Down
6 changes: 6 additions & 0 deletions src/structure/setIn.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,12 @@ const setInRecursor = (
return undefined
}
}

if (typeof current === 'string') {
// no need to remove properties, since strings cannot have custom properties anyways
return current
}

const { [key]: _removed, ...final } = current
return final
}
Expand Down