Created
March 29, 2023 17:25
-
-
Save wpcarro/6173bf89db6b0ac97db1d7effec721a1 to your computer and use it in GitHub Desktop.
Custom encoder/decoder with react-hook-form and zod.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import React from "react"; | |
| import { useForm } from "react-hook-form"; | |
| import { z } from "zod"; | |
| import { zodResolver } from "@hookform/resolvers/zod"; | |
| import DimensionID from "lib/quality/DimensionID"; | |
| //////////////////////////////////////////////////////////////////////////////// | |
| // Main | |
| //////////////////////////////////////////////////////////////////////////////// | |
| export default function Main() { | |
| const { | |
| register, | |
| handleSubmit, | |
| formState: { errors }, | |
| } = useForm({ | |
| mode: 'all', | |
| resolver: zodResolver(z.object({ | |
| transform: z.string().transform((x, ctx) => { | |
| const parsed = DimensionID.safeParse(x); | |
| if (!parsed.success) { | |
| ctx.addIssue({ code: z.ZodIssueCode.custom }); | |
| return z.NEVER; | |
| } | |
| return parsed.data; | |
| }), | |
| refine: z.string().refine(x => DimensionID.safeParse(x).success), | |
| }).strict()) | |
| }); | |
| return ( | |
| <div className="font-mono"> | |
| <form onSubmit={handleSubmit((x) => { console.log(x); })}> | |
| <div> | |
| <input type="text" {...register("transform")} /> | |
| <span className="text-red-500">{errors?.transform?.message}</span> | |
| </div> | |
| <div> | |
| <input type="text" {...register("refine")} /> | |
| <span className="text-red-500">{errors?.refine?.message}</span> | |
| </div> | |
| <button>submit</button> | |
| </form> | |
| </div> | |
| ); | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A couple observations:
transformandrefinewill validate the inputstransformandrefinewill model the value as a string (at least according towatch())onSubmit, however,transformwill be the fully parsedDimensionID, whilerefinewill still be a string