react-hook-form驗證

卓能文發表於2024-08-03
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.toString()}</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.toString()}</p>}
			</div>
			<input type="submit" />
		</form>
	);
};

相關文章