import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import i18next from "i18next";
import { z } from "zod";
import { zodI18nMap } from "zod-i18n-map";
// Import your language translation files
import translation from "zod-i18n-map/locales/zh-CN/zod.json";
import "../tailwind.css";
// lng and resources key depend on your locale.
i18next.init({
lng: "zh",
resources: {
zh: { zod: translation },
},
});
z.setErrorMap(zodI18nMap);
const schema = z.object({
name: z.string().min(1),
age: z.number().min(10),
});
export const Register = () => {
const {
register,
handleSubmit,
formState: { errors },
} = useForm({
resolver: zodResolver(schema),
});
return (
<form onSubmit={handleSubmit((d) => console.log(d))} noValidate>
<div className="block">
<input
{...register("name")}
className={errors.name?.message ? "invalid" : "valid"}
placeholder="name"
required
/>
{errors.name?.message && (
<p className="error">{errors.name?.message}</p>
)}
</div>
<div>
<input
type="number"
{...register("age", { valueAsNumber: true })}
className={errors.age?.message ? "invalid" : "valid"}
placeholder="age"
required
/>
{errors.name?.message && <p className="error">{errors.age?.message}</p>}
</div>
<input type="submit" />
</form>
);
};
标签:zh,errors,zod,name,form,react,hook,import,message
From: https://www.cnblogs.com/soarowl/p/18340569