Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save LucasJantschChitolina/f75b77988cecd17d7a3262df9c903455 to your computer and use it in GitHub Desktop.
Save LucasJantschChitolina/f75b77988cecd17d7a3262df9c903455 to your computer and use it in GitHub Desktop.
Numeric Input With Shadcn + Zod + RHF
"use client";
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";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
const formSchema = z.object({
quantity: z
.number({
message: "Quantity must be a number",
})
.min(1, "Quantity must be at least 1")
.max(1000, "Quantity cannot exceed 1000"),
});
type FormData = z.infer<typeof formSchema>;
export default function EditPage() {
const {
register,
handleSubmit,
formState: { errors, isSubmitting },
} = useForm<FormData>({
mode: "onChange",
resolver: zodResolver(formSchema),
defaultValues: {
quantity: 1,
},
});
const onSubmit = async (data: FormData) => {
console.log("Form submitted with data:", data);
// Handle form submission here
};
return (
<div className="container mx-auto py-8">
<Card className="max-w-md mx-auto">
<CardHeader>
<CardTitle>Edit Project</CardTitle>
<CardDescription>
Update the project quantity. Enter a valid number.
</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="quantity">Quantity</Label>
<Input
id="quantity"
type="number"
placeholder="Enter quantity"
{...register("quantity", { valueAsNumber: true })}
className={errors.quantity ? "border-red-500" : ""}
/>
{errors.quantity && (
<p className="text-sm text-red-500">
{errors.quantity.message}
</p>
)}
</div>
<Button type="submit" className="w-full" disabled={isSubmitting}>
{isSubmitting ? "Saving..." : "Save Changes"}
</Button>
</form>
</CardContent>
</Card>
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment