mirror of
https://github.com/LukeHagar/form.git
synced 2025-12-09 12:27:44 +00:00
feat: add back form validation (#505)
* initial attempt to add back form validation * uncomment tests * fixed form validation not running * onChange + onBlur * feat: mount method on FormApi * fix solid-form test case * fix checkLatest * add onMount logic + test * fix: run mount on proper API * test: add React Form onChange validation tests --------- Co-authored-by: aadito123 <aaditolkar123@gmail.com> Co-authored-by: aadito123 <63646058+aadito123@users.noreply.github.com>
This commit is contained in:
@@ -157,4 +157,49 @@ describe('useForm', () => {
|
||||
await user.click(getByText('Mount form'))
|
||||
await waitFor(() => expect(getByText('Form mounted')).toBeInTheDocument())
|
||||
})
|
||||
|
||||
it('should validate async on change for the form', async () => {
|
||||
type Person = {
|
||||
firstName: string
|
||||
lastName: string
|
||||
}
|
||||
const error = 'Please enter a different value'
|
||||
|
||||
const formFactory = createFormFactory<Person, unknown>()
|
||||
|
||||
function Comp() {
|
||||
const form = formFactory.useForm({
|
||||
onChange() {
|
||||
return error
|
||||
},
|
||||
})
|
||||
|
||||
return (
|
||||
<form.Provider>
|
||||
<form.Field
|
||||
name="firstName"
|
||||
children={(field) => (
|
||||
<input
|
||||
data-testid="fieldinput"
|
||||
name={field.name}
|
||||
value={field.state.value}
|
||||
onBlur={field.handleBlur}
|
||||
onChange={(e) => field.handleChange(e.target.value)}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<form.Subscribe selector={(state) => state.errorMap}>
|
||||
{(errorMap) => <p>{errorMap.onChange}</p>}
|
||||
</form.Subscribe>
|
||||
</form.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
const { getByTestId, getByText, queryByText } = render(<Comp />)
|
||||
const input = getByTestId('fieldinput')
|
||||
expect(queryByText(error)).not.toBeInTheDocument()
|
||||
await user.type(input, 'other')
|
||||
await waitFor(() => getByText(error))
|
||||
expect(getByText(error)).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -31,7 +31,7 @@ export function useForm<TData, FormValidator>(
|
||||
const api = new FormApi<TData>(opts)
|
||||
|
||||
api.Provider = function Provider(props) {
|
||||
useIsomorphicLayoutEffect(formApi.mount, [])
|
||||
useIsomorphicLayoutEffect(api.mount, [])
|
||||
return <formContext.Provider {...props} value={{ formApi: api }} />
|
||||
}
|
||||
api.Field = Field as any
|
||||
|
||||
Reference in New Issue
Block a user