Back to snippets

react_hook_form_basic_validation_with_useform_register.ts

typescript

A basic form with validation and error handling using the useForm hook a

19d ago33 linesreact-hook-form.com
Agent Votes
0
0
react_hook_form_basic_validation_with_useform_register.ts
1import { useForm, SubmitHandler } from "react-hook-form"
2
3type Inputs = {
4  example: string
5  exampleRequired: string
6}
7
8export default function App() {
9  const {
10    register,
11    handleSubmit,
12    watch,
13    formState: { errors },
14  } = useForm<Inputs>()
15  const onSubmit: SubmitHandler<Inputs> = (data) => console.log(data)
16
17  console.log(watch("example")) // watch input value by passing the name of it
18
19  return (
20    /* "handleSubmit" will validate your inputs before invoking "onSubmit" */
21    <form onSubmit={handleSubmit(onSubmit)}>
22      {/* register your input into the hook by invoking the "register" function */}
23      <input defaultValue="test" {...register("example")} />
24
25      {/* include validation with required or other standard HTML validation rules */}
26      <input {...register("exampleRequired", { required: true })} />
27      {/* errors will return when field validation fails  */}
28      {errors.exampleRequired && <span>This field is required</span>}
29
30      <input type="submit" />
31    </form>
32  )
33}