React-hook-form 输入字段匹配验证最佳实践

React-hook-form input fields match validation best practice

在处理 React-hook-form 时,输入字段匹配验证的最佳做法是什么?例如匹配email输入时等

在使用 React-hook-form 调查电子邮件匹配验证时发现了一个问题,同时试图通过他们的验证方法将错误消息与 "coupled elements" 分开。 ref只接受一个参数,用于React-hook-form register,而需要使用useRef访问current.value进行值匹配,如下:

import React, { useRef } from "react";
import ReactDOM from "react-dom";
import { useForm } from "react-hook-form";

function App() {
  const { register, handleSubmit, errors } = useForm();
  const inputEmail = useRef(null)
  const onSubmit = data => {
    console.log('onSubmit: ', JSON.stringify(data))
  }

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <label htmlFor="email">Email</label>
      <input
        name="email"
        type="email"
        ref={inputEmail}
      />
      {/* desired: show `email` error message */}
      <label htmlFor="email">Email confirmation</label>
      <input
        name="emailConfirmation"
        type="email"
        ref={register({
          validate: {
            emailEqual: value => (value === inputEmail.current.value) || 'Email confirmation error!',
          }
        })}
      />
      {errors.emailConfirmation && <p>{errors.emailConfirmation.message}</p>}
      <input type="submit" />
    </form>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

虽然这种模式在进行输入字段匹配时似乎是一个选项,但它不能很好地与 React-hook-form 配合使用!

例如,错误信息仅与一个输入案例耦合,没有针对每个独立字段的单独消息,或者其中一个输入字段没有分配给它的寄存器,这意味着 属性 required 未设置等

所以,我正在研究解决以下问题的良好做法或模式:

为此你可以使用 Yup 库,它很棒:

在实例化 useForm 并传递有效的 Yup 架构时,将 validationSchema 添加到您的配置对象。像这样:

const Schema = yup.object().shape({
  email: yup.string().required('Required field'),
  emailConfirmation: yup
    .string()
    .oneOf([yup.ref('email')], 'Emails must match')
    .required('Required field'),
});

// How to add it to your useForm
const { register } = useForm({
  validationSchema: Schema
})

您的组件应如下所示:

function App() {
  const { register, handleSubmit, errors } = useForm({
    validationSchema: Schema
  });

  const onSubmit = data => {
    console.log('onSubmit: ', JSON.stringify(data))
  }

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <label htmlFor="email">Email</label>
      <input
        name="email"
        type="email"
        ref={register}
      />
      {/* desired: show `email` error message */}
      <label htmlFor="email">Email confirmation</label>
      <input
        name="emailConfirmation"
        type="email"
        ref={register}
      />
      {errors.emailConfirmation && <p>{errors.emailConfirmation.message}</p>}
      <input type="submit" />
    </form>
  );
}

您不需要 inputEmail 的手动参考。相反,使用 getValues 方法获取整个表单的当前值。

const { register, getValues } = useForm()

然后注册两个输入并从自定义验证中调用 getValues

  <input
    name="email"
    type="email"
    ref={register}
  />
  <input
    name="emailConfirmation"
    type="email"
    ref={register({
      validate: {
        emailEqual: value => (value === getValues().email) || 'Email confirmation error!',
      }
    })}
  />