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:
Corbin Crutchley
2023-11-05 05:14:29 -08:00
committed by GitHub
parent 5d3f0fd946
commit 2fc941ed76
6 changed files with 632 additions and 18 deletions

View File

@@ -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()
})
})

View File

@@ -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