createForm
createForm is a function used to create a form instance. It takes one object as a requiredargument. The following example demonstrates all of its properties and methods.
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. |
| shouldFocusError | boolean | Enable or disable built-in focus management. |
defaultValues
The defaultValues prop populates the entire form with default values. You must provide defaultValues for all form fields to ensure type safety and proper form initialization.
createForm({
defaultValues: {
firstName: "",
lastName: ""
}
})mode
This option allows you to configure the validation strategy before a user submits the form. The validation occurs during the onSubmit event, which is triggered by invoking the handleSubmit function.
| Name | Type | Description |
|---|---|---|
| onSubmit | string | Validation is triggered on the submit event. |
| onBlur | string | Validation is triggered on the blur event. |
| onChange | string | Validation is triggered on the change event for each input, leading to multiple re-renders. |
| onTouched | string | Validation is initially triggered on the first blur event. After that, it is triggered on every change event. |
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>
)
}shouldFocusError
When set to true (default), and the user submits a form that fails validation, focus is set on the first field with an error.
The focus order is based on the register order.
createForm({
defaultValues: {
firstName: "",
lastName: ""
},
shouldFocusError: false
})Returns
The following list contains reference to createForm return props.
- register
- formState
- values
- errors
- handleSubmit
- reset
- setError
- clearErrors
- setValue
- getValues
- trigger