Yup
You can find full example at StackBlitz.
Check Yup documentation for more details.
Define a schema:
import { object, string, boolean } from 'yup'
export const exampleSchema = object({
email: string().email().required(),
name: string().required(),
consent: boolean().isTrue()
})
When using TypeScript, infer form values type from the schema:
import { InferType } from 'yup'
export type ExampleFormValues = InferType<typeof exampleSchema>Connect schema to the form:
import { createForm } from 'solid-hook-form'
import { yupResolver } from '@hookform/resolvers/yup'
import { exampleSchema } from './example_schema'
export const ExampleForm = () => {
const form = createForm({
defaultValues: {
email: '',
name: '',
consent: false
},
resolver: yupResolver(exampleSchema)
})
const { errors, register, handleSubmit } = form
const onSubmit = (values) => {
console.log(values)
}
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('email')} aria-invalid={Boolean(errors.email)} />
{errors.email && <p role="alert">{errors.email.message}</p>}
<input {...register('name')} aria-invalid={Boolean(errors.name)} />
{errors.name && <p role="alert">{errors.name.message}</p>}
<input type="checkbox" {...register('consent')} aria-invalid={Boolean(errors.consent)} />
{errors.consent && <p role="alert">{errors.consent.message}</p>}
<button type="submit">Save</button>
</form>
)
}