在Shadcn React Hook Form和Zod中将可为空或未定义的字符串预处理

问题描述 投票:0回答:1

我有很多想要从 API 填充的字段。我如何

preprocess
它们,如果它是
null
undefined
,只需将它们转换为字符串?

我的问题是,如果它是

"null"
,我下面的代码输出为 
null

代码

const formSchema = z.object({
    contact: z.object({
        first_name: z.string().min(1, { message: "Enter first name" }),
        last_name: z.string().min(1, { message: "Enter last name" }),
        title: z.preprocess((val) => String(val), z.string()),
    }),

    organization: z.object({
        name: z.string().min(1, { message: "Enter organization name" }),
    }),
});

const form = useForm<FormData>({
    mode: "onTouched",
    resolver,
    defaultValues: {
        contact: { ...recipient.contact },
        organization: { ...recipient.organization },
    },
});

<FormField
    control={form.control}
    name="contact.title"
    render={({ field }) => (
        <FormItem>
            <FormLabel>Title</FormLabel>
            <FormControl>
                <Input placeholder="Enter title" {...field} />
            </FormControl>
            <FormMessage />
        </FormItem>
    )}
/>
javascript reactjs react-hook-form zod
1个回答
0
投票

我想你所需要的只是Nullish Coalescing Operator

// ...
title: z.preprocess((val) => String(val ?? ""), z.string()),
// ...
© www.soinside.com 2019 - 2024. All rights reserved.