在你自己的项目里运行这个示例:npx shadcn@latest add button input label
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { z } from "zod"
import { Button } from "./components/ui/button"
import { Input } from "./components/ui/input"
import { Label } from "./components/ui/label"
const schema = z.object({
email: z.email("请输入有效的邮箱地址"),
password: z.string().min(8, "至少需要 8 个字符").regex(/[0-9]/, "请至少包含一个数字"),
})
type FormValues = z.infer<typeof schema>
export default function App() {
const {
register,
handleSubmit,
formState: { errors },
} = useForm<FormValues>({ resolver: zodResolver(schema) })
const onSubmit = (values: FormValues) => {
alert("已登录:" + values.email)
}
return (
<form onSubmit={handleSubmit(onSubmit)} className="flex flex-col gap-4 p-5">
<div className="flex flex-col gap-2">
<Label htmlFor="email">邮箱</Label>
{}
<Input id="email" {...register("email")} />
{}
{errors.email && (
<p className="text-sm text-destructive">{errors.email.message}</p>
)}
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="password">密码</Label>
<Input id="password" type="password" {...register("password")} />
{errors.password && (
<p className="text-sm text-destructive">{errors.password.message}</p>
)}
</div>
<Button type="submit">登录</Button>
</form>
)
}