【问题标题】:Unable to validate conditionally with zod validation无法使用 zod 验证有条件地验证
【发布时间】:2023-02-13 19:43:31
【问题描述】:

我有一个带有单选按钮的表单,其中包含三个输入字段。我有一个提交按钮,可以验证是否只有一个输入字段被正确输入。我在 zod 验证中使用了 refine() 但没有任何反应。它总是验证三个输入,这里有什么问题?

export const FormSchema = z.object({
  firstname: z.string().min(1, {message:"Please enter a name."}),
  address: z.string().min(1, {message:"Please enter an address."}),
  email: z.string().min(1, {message:"Please enter an email."}),
}).refine(
    data => data.firstname || data.address || data.email,
    "Either first or second or third should be filled in."
  );;

export type FormSchemaType = z.infer<typeof FormSchema>;

const [searchOption, setSearchOption] = useState("searchName");

<FormProvider {...methods}>
  <form onSubmit={handleSubmit(onFormSubmit)} noValidate>
   <RadioButton id="1" value="searchName"/>
   <InputField
     type="text"
     name="firstname"
     label="First Name"
   />
   <InputField
     type="text" 
     name="address"
     label="Address Name"
   />
   <InputField
     type="email" 
     name="email"
     label="E-mail"
   />      
 </form>
</FormProvider>

【问题讨论】:

    标签: reactjs typescript zod


    【解决方案1】:

    您应该添加消息,尝试使用:

    .refine((data) => data.firstname || data.address || data.email, {
        message: "Either first or second or third should be filled in."
      });
    

    【讨论】:

      猜你喜欢
      • 2022-11-20
      • 2021-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-07
      相关资源
      最近更新 更多