createForm
createForm is function used to create a form instance. It takes one object as optional argument. The following example demonstrates all of its properties and methods.
useForm alias will be removed in the future.
Props
| Name | Type | Description |
|---|---|---|
| defaultValues | Object | Default values for the form. |
| mode | string | Validation strategy. Defaults to 'onChange'. |
| resolver | Resolver | Integrates with your preferred schema validation library. |
defaultValues
The defaultValues prop populates the entire form with default values. It is recommended to use defaultValues for the entire form.
createForm({
defaultValues: {
firstName: "",
lastName: ""
}
});mode
This option allows you to configure the validation strategy.
| Name | Type | Description |
|---|---|---|
| onSubmit | string | Validation is triggered on the submit event. |
| onChange | string | Validation is triggered on the change event for each input. Only updated fields will be re-rendered. |
createForm({
mode: 'onChange'
});resolver
This function allows you to use any external validation library such as Yup, Zod and many others. The goal is to make sure you can seamlessly integrate whichever validation library you prefer. If you're not using a library, you can always write your own logic to validate your forms.
Install @hookform/resolvers package
npm install @hookform/resolversDefine a schema:
import z, { object, string, number } from "zod";
const formSchema = object({
name: string().min(1, "Required"),
age: number()
});
type FormValues = z.infer<typeof formSchema>;
Apply resolver:
import { zodResolver } from '@hookform/resolvers'
import { createForm } from 'solid-hook-form'
const ExampleForm = () => {
const { register, handleSubmit } = createForm<FormValues>({
defaultValues: {
name: '',
age: 0
},
resolver: zodResolver(formSchema)
})
const onSubmit = (values: FormValues) => {
console.log(values)
}
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('name')} />
<input type="number" {...register('age', { valueAsNumber: true })} />
<button type="submit">Save</button>
</form>
)
}Returns
The following list contains reference to createForm return props.
- register
- handleSubmit
- values
- errors
- isValid
- getValues
- setValue
- reset