使用 yup 进行简单的反应表单验证

Simple react form validation with yup

我正在尝试使用 yup 和 react-hook-form 学习表单验证,并且理想情况下希望将验证设置为还需要至少两个不同名称的单选选项中的一个,但首先要了解为什么 isValid 变量为假。

这是我的代码:

import React from "react";
import { useForm } from "react-hook-form";
import * as yup from "yup"

const App = () => {
  const { register, handleSubmit, watch, errors } = useForm();
  const onSubmit = async data => {
    console.log('form data', data);
    const isValid = await schema.isValid();
    console.log('isValid', isValid);
  }

  return (
    <>
    {console.log('errors', errors)}
    <form onSubmit={handleSubmit(onSubmit)}>
      <input name="name" defaultValue="test" ref={register} />
      
      <input name="nameTwo" ref={register({ required: true })} />
      {errors.exampleRequired && <span>This field is required</span>}

      <label>
        <input
          name="test"
          type="radio"
          ref={register}
          value="test"
        />
    </label>

    <label>
        <input
          name="testTwo"
          type="radio"
          ref={register}
          value="testTwo"
        />
    </label>
      
      <input type="submit" />
    </form>
    </>
  );
}

const schema = yup.object().shape({
  name: yup.string(),
  nameTwo: yup.string().required(),
  test: yup.string(),
  testTwo: yup.string()
})

export default App

所以schema只按要求定义了一个字段(nameTwo),但即使填写那个字段它仍然是错误的。为什么 isValid 不是真的?如何最好地使两个单选按钮(testtestTwo)中的任何一个成为必填项?

Stackblitz 演示:https://stackblitz.com/edit/react-93vahd

谢谢

isValid 属性 在 useForm 挂钩返回的 formState 对象中可用。

您会注意到除非 Yup 验证通过,否则不会调用 onSubmit。因此,在 onSubmit 回调内部检查时,isValid 将始终为真。

import React from 'react';
import { useForm } from 'react-hook-form';
import * as yup from 'yup';

const App = () => {
  const {
    register,
    handleSubmit,
    errors,
    formState: { isValid }
  } = useForm();
  const onSubmit = async data => {
    console.log('form data', data);
  };

  return (
    <>
      {console.log('isValid', isValid)}
      {console.log('errors', errors)}
      <form onSubmit={handleSubmit(onSubmit)}>
        <input name="name" defaultValue="test" ref={register} />

        <input name="nameTwo" ref={register({ required: true })} />
        {errors.exampleRequired && <span>This field is required</span>}

        <label>
          <input name="test" type="radio" ref={register} value="test" />
        </label>

        <label>
          <input name="testTwo" type="radio" ref={register} value="testTwo" />
        </label>

        <input type="submit" />
      </form>
    </>
  );
};

const schema = yup.object().shape({
  name: yup.string(),
  nameTwo: yup.string().required(),
  test: yup.string(),
  testTwo: yup.string()
});

export default App;