我的表单使用zod和react hooks表单。我有价格的输入字段。为了防止不受控制的输入错误,我们需要给defaultValues,但它迫使我给价格默认值0。我不希望它是零。我能把它变成空的吗?
import * as z from "zod";
export const ProductSchema = z.object({
title: z.string().min(2),
price: z.number().positive(),
discount: z.number().int().min(0).max(100),
...
})
export type ProductType = z.infer<typeof ProductSchema>;
我的表格是这样的:
const form = useForm<ProductType>({
resolver: zodResolver(ProductSchema),
defaultValues: {
title: "",
price: 0,
discount: 0,
....
},
});
为了造型,我使用了shadcn表单组件:
<FormField
control={control}
render={({ field }) => (
<FormItem>
<FormLabel>Price</FormLabel>
<Input
{...field}
disabled={isPending}
placeholder="Price of product"
type="number"
className="shadow-sm focus:ring-primary-500 focus:border-primary-500 sm:text-sm border-gray-300 rounded-md bg-white"
/>
<FormMessage>{errors.price?.message}</FormMessage>
</FormItem>
)}
name="price"
/>