代码之家  ›  专栏  ›  技术社区  ›  Apollo Vostok

如何在zod和react hook形式中给出数字类型的默认值(但不是零)?

  •  0
  • Apollo Vostok  · 技术社区  · 2 年前

    我的表单使用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"
                    />
    
    
    1 回复  |  直到 2 年前
        1
  •  1
  •   DMabulage    2 年前

    在你的zod模式中

    price: z
        .string()
        .min(1, 'cannot be empty')
        .default('')
        .refine(     
          (val) => !isNaN(Number(val)),
          { message: 'Invalid price' }
        )
    

    在这里,它只接受空字符串和数字。

    现在可以将默认值设置为

     defaultValues: {
          title: "",
          price: "",
          discount: 0,
          ....
        },