【问题标题】:react-hook-form use mutiple resolverreact-hook-form 使用多个解析器
【发布时间】:2022-01-25 13:00:00
【问题描述】:

我正在尝试创建这样的一般输入

const TextInput = ({
  name,
  register = () => {},
  errors,
  serverErrors,
  ...props
}) => {
  return (
    <div >
      <input
        type="text"
        {...register(name, {
          pattern: { value: /^[A-Za-z]+$/i, message: "Invalid Input" },
        })}
        {...props}
      />
      {errors?.[name] && (
        <span className="text-errorColor">{errors?.[name]?.message}</span>
      )}
    </div>
  );
};

我将在表单中使用此输入并使用 Yup 验证此表单


const schema = yup
  .object({
    first_name: yup
      .string()
      .required("This field is required")
      .max(20, "max 20 characters"),
  })
  .required();

const SignupForm = ({ signUpContact, signUpType }) => {
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(schema),
  });
  return (
    <form onSubmit={handleSubmit(onSubmit)}>
            <TextInput
              name="first_name"
              register={register}
              errors={errors}
              serverErrors={error}
              placeholder="First Name"
            />
       </form>
  );
};

但问题是 TextInput Competent 中的验证没有运行 我想我不能将注册验证与 Yup 验证一起使用。 如您所见,我不会在每次使用 TextInput 时重复验证 [A-Za-z],有什么方法可以做到这一点吗?

【问题讨论】:

    标签: reactjs react-hooks react-hook-form


    【解决方案1】:

    对于输入,只需使用 react-hook-form 注册字段

          <input
            type="text"
            {...register(name)}
            {...props}
          />
    

    使用 yup 处理所有的验证逻辑

    yup
    .string()
    .trim()
    .matches(/^[A-Za-z]+$/i , 'Invalid Input')
    .max(20, "max 20 characters"),
    .required();
    

    【讨论】:

    • 如果我使用这个,我每次使用TextInput都会复制代码,我不会这样做
    猜你喜欢
    • 2021-11-15
    • 2021-05-16
    • 1970-01-01
    • 2021-10-04
    • 1970-01-01
    • 2022-01-15
    • 2022-12-21
    • 2020-06-02
    • 2021-07-10
    相关资源
    最近更新 更多