繁体   English   中英

如何使用 react-hook-form 中的单选按钮控制带有错误验证的表单?

[英]How to control form with error validations with Radio buttons in react-hook-form?

在 React 项目中,我有某些单选按钮,并且我想提供验证,即当未选中时会引发错误。 请参阅下面的代码以供参考

const defaultValues = {
  radioValue: ""
};

const radioData = [
  {
    radio: "2:00 PM"
  },
  {
    radio: "3:00 PM"
  },
  {
    radio: "5:00 PM"
  },
  {
    radio: "10:00 AM"
  },
  {
    radio: "9:30 AM"
  }
];


const { handleSubmit, reset, control, register, errors } = useForm({
    defaultValues
  });

const [durationValue, setDurationValue] = useState("1");

<form noValidate autoComplete="off" onSubmit={handleSubmit(onSubmit)}>
        {radioData.map((data, i) => {
          return (
            <ToggleButton
              className="toggleButtonNew2"
              key={i}
              type="radio"
              active="true"
              variant="light"
              name="radio2"
              value={data.radio}
              checked={durationValue === data.radio}
              onChange={(e) => {
                handleChange(e);
              }}
            >
              {data.radio + " min"}
            </ToggleButton>
          );
        })}
        <br />
        <br />
        <button type="submit">Submit</button>
      </form>

我已尝试使用此代码,如下所示:

<Controller 
  control={control}
  render = {({ ref, onChange: handleChange, value }) => (
    <ToggleButton
              className="toggleButtonNew2"
              key={i}
              ref={ref}
              type="radio"
              active="true"
              variant="light"
              name="radioValue"
              value={data.radio}
              checked={durationValue === data.radio}
              onChange={(e) => {
                handleChange(e);
              }}
            >
              {data.radio + " min"}
            </ToggleButton>
  )}
  />

  <small className="form-text text-danger">
           {
             errors.radioValue && <p className="errorMessage">{errors.radioValue.message}</p>
           }
  </small>

但是,这个给出了错误“path.split 不是函数”。 使用单选按钮启用 react-hook-form 验证的更好解决方案是什么?

请参考这个链接

CodeSandbox 链接为: https://codesandbox.io/s/set-countdown-timer-react-js-forked-m6xei

您需要添加逻辑以检查是否单击了切换按钮,方法是使用使用 null/undefined 值初始化的durationValue state并在onSubmit method中检查 null/undefined。 在下面的代码段中添加了相同的代码。

export default function App() {
  const { handleSubmit, reset, control, register, errors } = useForm({
    defaultValues
  });

  const [durationValue, setDurationValue] = useState(null);
  const [formError, setFormError] = useState(undefined);

  const onSubmit = (e) => {
    if (!durationValue) {
      setFormError({
        message: "not selected any input"
      });
    }
  };
  const handleChange = (e) => {
    const newData = e.target.value;
    console.log("Duration DATA", newData);
    var elems = document.querySelectorAll(".toggleButtonNew2.active");
    [].forEach.call(elems, function (el) {
      el.classList.remove("active");
    });
    e.target.closest("label").classList.toggle("active");
    setDurationValue(newData);
    setFormError(undefined);
  };

  return (
    <>
      <form noValidate autoComplete="off" onSubmit={handleSubmit(onSubmit)}>
        {radioData.map((data, i) => {
          return (
            <ToggleButton
              className="toggleButtonNew2"
              key={i}
              type="radio"
              active="true"
              variant="light"
              name="radio2"
              value={data.radio}
              checked={durationValue === data.radio}
              onChange={(e) => {
                handleChange(e);
              }}
            >
              {data.radio}
            </ToggleButton>
          );
        })}
        <br />
        <br />
        <button type="submit">Submit</button>
      </form>
      <small className="form-text text-danger">
        {formError?.message && (
          <p className="errorMessage">{formError.message}</p>
        )}
      </small>
    </>
  );
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM