【问题标题】:react-hook-form: How to validate when either of two fileds are requiredreact-hook-form:如何验证何时需要两个字段中的任何一个
【发布时间】:2021-11-06 05:01:53
【问题描述】:

我有两个字段itemlistitemlistUpload

我正在使用react-hook-forms。我希望用户提供其中任何一个。其中之一是必需的

如何进行验证

import { useForm, Controller } from "react-hook-form";
import {
  Col,
  Row,
  Form,
  FormGroup,
  InputGroup,
  Input,
  Container
} from "reactstrap";

export default function App() {
  const onSubmit = (data) => {
    console.log(data);
  };

  const { control, handleSubmit } = useForm();

  return (
    <Container>
      <Form onSubmit={handleSubmit(onSubmit)}>
        <Row className="m-3">
          <Col>
            <Controller
              name="itemlist"
              control={control}
              render={({ field: { ref, ...field } }) => (
                <Input
                  {...field}
                  type="textarea"
                  rows={10}
                  placeholder="itemlist"
                  required
                  innerRef={ref}
                />
              )}
            />
          </Col>
        </Row>
        <Row className="m-3">
          <Col>
            <FormGroup row className="mr-md-1">
              <InputGroup className="mb-3">
                <Controller
                  name="itemlist2"
                  control={control}
                  render={({ field: { ref, ...field } }) => (
                    <Input
                      {...field}
                      type="file"
                      required
                      innerRef={ref}
                    />
                  )}
                />
              </InputGroup>
            </FormGroup>
          </Col>
        </Row>
      </Form>
    </Container>
  );
}

这里是密码箱https://codesandbox.io/s/bitter-grass-erz7t

【问题讨论】:

    标签: reactjs react-hook-form


    【解决方案1】:

    从两个输入中删除“必需”属性,并使用 useForm 中的 setError 和 clearErrors 函数手动验证字段。 (https://react-hook-form.com/api/useform/seterror, https://react-hook-form.com/api/useform/clearerrors)

    在提交表单时检查其中一个字段是否已填写,如果没有,则设置一个新错误并且不记录数据。然后在输入的 onChange 函数中添加逻辑,以在输入数据后清除错误。

    import "./styles.css";
    import { useForm, Controller } from "react-hook-form";
    import {
      Col,
      Row,
      Form,
      FormGroup,
      InputGroup,
      Input,
      Container
    } from "reactstrap";
    
    export default function App() {
      const onSubmit = (data) => {
        if (!data.itemlist && !data.itemlist2) {
          setError("neitherItemlist", {
            type: "manual",
            message: "You must fill out either itemlist or itemlist1"
          });
          return;
        }
        console.log(data);
      };
    
      const {
        control,
        handleSubmit,
        setError,
        formState: { errors },
        clearErrors
      } = useForm();
    
      return (
        <Container>
          <Form onSubmit={handleSubmit(onSubmit)}>
            <Row className="m-3">
              <Col>
                <Controller
                  name="itemlist"
                  control={control}
                  render={({ field: { ref, ...field } }) => (
                    <Input
                      {...field}
                      type="textarea"
                      rows={10}
                      placeholder="itemlist"
                      innerRef={ref}
                      onChange={(e) => {
                        field.onChange(e);
                        clearErrors("neitherItemlist");
                      }}
                    />
                  )}
                />
              </Col>
            </Row>
            <Row className="m-3">
              <Col>
                <FormGroup row className="mr-md-1">
                  <InputGroup className="mb-3">
                    <Controller
                      name="itemlist2"
                      control={control}
                      render={({ field: { ref, ...field } }) => (
                        <Input
                          {...field}
                          type="file"
                          innerRef={ref}
                          onChange={(e) => {
                            field.onChange(e);
                            clearErrors("neitherItemlist");
                          }}
                        />
                      )}
                    />
                  </InputGroup>
                </FormGroup>
              </Col>
            </Row>
            {errors.neitherItemlist && (
              <p style={{ color: "red" }}>{errors.neitherItemlist.message}</p>
            )}
            <input type="submit" />
          </Form>
        </Container>
      );
    }
    

    https://codesandbox.io/s/confident-brook-14zwj?file=/src/App.js:0-2208

    【讨论】:

    • 另外,如果这两个项目都没有提供,我想显示请选择其中一个项目
    • 这个问题,这个错误只有在提交函数运行后才会显示。但其他表单字段错误显示在提交功能之前。
    猜你喜欢
    • 1970-01-01
    • 2021-06-18
    • 2021-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-21
    • 2022-06-23
    • 2021-05-22
    相关资源
    最近更新 更多