javascript 更正Zod和React Hook表单中的错误消息

jw5wzhpr  于 2023-09-29  发布在  Java
关注(0)|答案(1)|浏览(144)

我想验证一个电话号码。如果它有一个值,那么它应该输出“无效的移动的号码格式”。如果为空,则应输出“需要移动的号码”。
目前,它总是输出为“无效的移动的号码格式”。
我使用Zodreact-hook-formlibphonenumber-js

import { isValidPhoneNumber } from "libphonenumber-js";

...

const schema = zod.object({
  firstName: zod
    .string({
      required_error: "First name is required.",
    })
    .nonempty("First name is required."),
  lastName: zod
    .string({
      required_error: "Last name is required.",
    })
    .nonempty("Last name is required."),
  contactNumber: zod
    .string({
      required_error: "Mobile number is required.",
    })
    .transform((value) => `+${value}`)
    .refine(isValidPhoneNumber, "Invalid mobile number format.")
    .transform((value) => value.slice(1)),
});

...

<Controller
  control={control}
  name="contactNumber"
  rules={{ required: true }}
  render={({ field: { ref, ...field }, ...props }) => (
    <StyledPhoneInput
      enableSearch
      enableTerritories
      specialLabel="Mobile number "
      inputProps={{
        ref,
        required: true,
        placeholder: "+84",
      }}
      country={"vn"}
      autoFormat
      field={field}
      muiProps={{ required: true, fullWidth: true }}
      {...props}
    />
  )}
/>
ljsrvy3e

ljsrvy3e1#

我不知道什么是最小有效电话号码,但基本上看起来你需要验证contactNumber字段上的一些最小输入。据我所知,指定required_error prop似乎只需要一个 defined 值。
例如,如果你有 justfirstName: zod.string({ required_error: "First name is required." }),那么值""被接受,而undefined抛出错误"First name is required.".nonempty验证器似乎将字符串强制转换为字符数组,并Assert它不为空。
您可以AssertcontactNumber也有一些最小的非零输入量。
范例:

contactNumber: zod
  .string({
    required_error: "Mobile number is required.",
  })
  .min(1, "Mobile number is required.")
  .transform((value) => `+${value}`)
  .refine(isValidPhoneNumber, "Invalid mobile number format.")
  .transform((value) => value.slice(1)),

const schema = zod.object({
  firstName: zod
    .string({
      required_error: "First name is required.",
    })
    .nonempty("First name is required."),
  lastName: zod
    .string({
      required_error: "Last name is required.",
    })
    .nonempty("Last name is required."),
  contactNumber: zod
    .string({
      required_error: "Mobile number is required.",
    })
    .min(10, "Mobile number is too short.")
    .transform((value) => `+${value}`)
    .refine(isValidPhoneNumber, "Invalid mobile number format.")
    .transform((value) => value.slice(1)),
});
schema.parse({
  firstName: "Norman",
  lastName: "Newman",
  contactNumber: undefined, // Number is required
});

schema.parse({
  firstName: "Bob",
  lastName: "Sacamano",
  contactNumber: "5555555", // Too short
});

schema.parse({
  firstName: "Cosmo",
  lastName: "Kramer",
  contactNumber: "2125555555", // Invalid format
});

const result = schema.parse({
  firstName: "Jerry",
  lastName: "Seinfeld",
  contactNumber: "12125555555", // Valid
});

相关问题