我想保留文件上传可选,但如果未上传文件,则不会提交表单

发布于 2025-01-10 18:38:07 字数 6113 浏览 0 评论 0原文

我创建了一个表单,我希望文件上传是可选的,它位于 React & 中。反应引导程序。但是,当我不上传文件时,表单不会被提交。

我正在使用自定义表单验证,效果很好。另外,在这里我尝试将单个文件上传到后端,这也工作正常。但如果没有文件上传,我无法提交表单。

const Contact = () => {
  const [files, setFiles] = useState(null);
  const [successful, setSuccessful] = useState(false);
  const [form, setForm] = useState({});
  const [errors, setErrors] = useState({});

  const setField = (field, value) => {
    setForm({
      ...form,
      [field]: value,
    });

    if (!!errors[field])
      setErrors({
        ...errors,
        [field]: null,
      });
  };

  const { firstName, lastName, email, city, company, howCanWeHelp, NDA } = form;

  const findFormErrors = () => {
    const newErrors = {};

    if (!firstName || firstName === "") newErrors.firstName = "cannot be blank";
    if (!lastName || lastName === "") newErrors.lastName = "cannot be blank";
    if (!email || !email.includes("@")) newErrors.email = "enter a valid email";
    if (!company || company === "") newErrors.company = "cannot be blank";
    if (!howCanWeHelp || howCanWeHelp === "")
      newErrors.howCanWeHelp = "cannot be blank";

    return newErrors;
  };

  const onFileUpload = async (e) => {
    setFiles(e.target.files[0]);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();

    const newErrors = findFormErrors();

    if (Object.keys(newErrors).length > 0) {
      setErrors(newErrors);
    } else {
      const formData = new FormData();
      formData.append("firstName", firstName);
      formData.append("lastName", lastName);
      formData.append("email", email);
      formData.append("city", city);
      formData.append("company", company);
      formData.append("howCanWeHelp", howCanWeHelp);
      formData.append("NDA", NDA);
      formData.append("file", files);

      const companyForm = `${process.env.REACT_APP_PUBLIC_REQUEST}/company-form`;

      await Axios.post(companyForm, formData, {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      })
        .then(() => {
          setSuccessful(true);
        })
        .catch((error) => console.error(error));
    }
  };

  return (
    <div className={`${styles.container}`}>
      <Form onSubmit={handleSubmit}>
        <Row className={styles["contact__row"]}>
          <Col className={styles["contact__form-content"]}>
            <h2>Contact Us</h2>

            <Form.Group className="mb-3">
              <Form.Label>First Name*</Form.Label>
              <Form.Control
                onChange={(e) => setField("firstName", e.target.value)}
                type="text"
                isInvalid={!!errors.firstName}
              />
              <Form.Control.Feedback type="invalid">
                {errors.firstName}
              </Form.Control.Feedback>
            </Form.Group>

            <Form.Group className="mb-3">
              <Form.Label>Last Name*</Form.Label>
              <Form.Control
                onChange={(e) => setField("lastName", e.target.value)}
                type="text"
                isInvalid={!!errors.lastName}
              />
              <Form.Control.Feedback type="invalid">
                {errors.lastName}
              </Form.Control.Feedback>
            </Form.Group>

            <Form.Group className="mb-3">
              <Form.Label>Email*</Form.Label>
              <Form.Control
                onChange={(e) => setField("email", e.target.value)}
                type="text"
                isInvalid={!!errors.email}
              />
              <Form.Control.Feedback type="invalid">
                {errors.email}
              </Form.Control.Feedback>
            </Form.Group>

            <Form.Group className="mb-3">
              <Form.Label>City:</Form.Label>
              <Form.Control
                onChange={(e) => setField("city", e.target.value)}
                type="text"
              />
            </Form.Group>

            <Form.Group className="mb-3">
              <Form.Label>Company:</Form.Label>
              <Form.Control
                onChange={(e) => setField("company", e.target.value)}
                type="text"
                isInvalid={!!errors.company}
              />
              <Form.Control.Feedback type="invalid">
                {errors.company}
              </Form.Control.Feedback>
            </Form.Group>

            <Form.Group className="mb-3">
              <Form.Label>How we can help you?*</Form.Label>
              <Form.Control
                onChange={(e) => setField("howCanWeHelp", e.target.value)}
                as="textarea"
                row={4}
                isInvalid={!!errors.howCanWeHelp}
              />
              <Form.Control.Feedback type="invalid">
                {errors.howCanWeHelp}
              </Form.Control.Feedback>
            </Form.Group>

            <Form.Group className="mb-3">
              <Form.Label>Attach your files here:</Form.Label>
              <Form.Control onChange={onFileUpload} type="file" />
            </Form.Group>

            <div className={styles["contact__button-checkbox"]}>
              <Form.Group className="mb-3">
                <Form.Check
                  defaultChecked={NDA}
                  onChange={(e) => {
                    setField("NDA", e.target.checked);
                  }}
                  type="checkbox"
                  label="Send NDA"
                />
              </Form.Group>
              <Button
                disabled={successful}
                type="submit"
                variant="outline-dark"
              >
                {successful ? "Sent Successfully" : "SEND"}
              </Button>
            </div>
          </Col>

I've created a form where I want the file upload to be optional, it's in React & React Bootstrap. But when I don't upload the file the form is not being submitted.

I'm using a custom form validation, and it works fine. Also, here I'm trying to upload the single file to the backend, which is also working fine. But I am not able to submit the form without file upload.

const Contact = () => {
  const [files, setFiles] = useState(null);
  const [successful, setSuccessful] = useState(false);
  const [form, setForm] = useState({});
  const [errors, setErrors] = useState({});

  const setField = (field, value) => {
    setForm({
      ...form,
      [field]: value,
    });

    if (!!errors[field])
      setErrors({
        ...errors,
        [field]: null,
      });
  };

  const { firstName, lastName, email, city, company, howCanWeHelp, NDA } = form;

  const findFormErrors = () => {
    const newErrors = {};

    if (!firstName || firstName === "") newErrors.firstName = "cannot be blank";
    if (!lastName || lastName === "") newErrors.lastName = "cannot be blank";
    if (!email || !email.includes("@")) newErrors.email = "enter a valid email";
    if (!company || company === "") newErrors.company = "cannot be blank";
    if (!howCanWeHelp || howCanWeHelp === "")
      newErrors.howCanWeHelp = "cannot be blank";

    return newErrors;
  };

  const onFileUpload = async (e) => {
    setFiles(e.target.files[0]);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();

    const newErrors = findFormErrors();

    if (Object.keys(newErrors).length > 0) {
      setErrors(newErrors);
    } else {
      const formData = new FormData();
      formData.append("firstName", firstName);
      formData.append("lastName", lastName);
      formData.append("email", email);
      formData.append("city", city);
      formData.append("company", company);
      formData.append("howCanWeHelp", howCanWeHelp);
      formData.append("NDA", NDA);
      formData.append("file", files);

      const companyForm = `${process.env.REACT_APP_PUBLIC_REQUEST}/company-form`;

      await Axios.post(companyForm, formData, {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      })
        .then(() => {
          setSuccessful(true);
        })
        .catch((error) => console.error(error));
    }
  };

  return (
    <div className={`${styles.container}`}>
      <Form onSubmit={handleSubmit}>
        <Row className={styles["contact__row"]}>
          <Col className={styles["contact__form-content"]}>
            <h2>Contact Us</h2>

            <Form.Group className="mb-3">
              <Form.Label>First Name*</Form.Label>
              <Form.Control
                onChange={(e) => setField("firstName", e.target.value)}
                type="text"
                isInvalid={!!errors.firstName}
              />
              <Form.Control.Feedback type="invalid">
                {errors.firstName}
              </Form.Control.Feedback>
            </Form.Group>

            <Form.Group className="mb-3">
              <Form.Label>Last Name*</Form.Label>
              <Form.Control
                onChange={(e) => setField("lastName", e.target.value)}
                type="text"
                isInvalid={!!errors.lastName}
              />
              <Form.Control.Feedback type="invalid">
                {errors.lastName}
              </Form.Control.Feedback>
            </Form.Group>

            <Form.Group className="mb-3">
              <Form.Label>Email*</Form.Label>
              <Form.Control
                onChange={(e) => setField("email", e.target.value)}
                type="text"
                isInvalid={!!errors.email}
              />
              <Form.Control.Feedback type="invalid">
                {errors.email}
              </Form.Control.Feedback>
            </Form.Group>

            <Form.Group className="mb-3">
              <Form.Label>City:</Form.Label>
              <Form.Control
                onChange={(e) => setField("city", e.target.value)}
                type="text"
              />
            </Form.Group>

            <Form.Group className="mb-3">
              <Form.Label>Company:</Form.Label>
              <Form.Control
                onChange={(e) => setField("company", e.target.value)}
                type="text"
                isInvalid={!!errors.company}
              />
              <Form.Control.Feedback type="invalid">
                {errors.company}
              </Form.Control.Feedback>
            </Form.Group>

            <Form.Group className="mb-3">
              <Form.Label>How we can help you?*</Form.Label>
              <Form.Control
                onChange={(e) => setField("howCanWeHelp", e.target.value)}
                as="textarea"
                row={4}
                isInvalid={!!errors.howCanWeHelp}
              />
              <Form.Control.Feedback type="invalid">
                {errors.howCanWeHelp}
              </Form.Control.Feedback>
            </Form.Group>

            <Form.Group className="mb-3">
              <Form.Label>Attach your files here:</Form.Label>
              <Form.Control onChange={onFileUpload} type="file" />
            </Form.Group>

            <div className={styles["contact__button-checkbox"]}>
              <Form.Group className="mb-3">
                <Form.Check
                  defaultChecked={NDA}
                  onChange={(e) => {
                    setField("NDA", e.target.checked);
                  }}
                  type="checkbox"
                  label="Send NDA"
                />
              </Form.Group>
              <Button
                disabled={successful}
                type="submit"
                variant="outline-dark"
              >
                {successful ? "Sent Successfully" : "SEND"}
              </Button>
            </div>
          </Col>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一身仙ぐ女味 2025-01-17 18:38:07

由于您对每个单击的提交进行验证,因此您的某些验证可能会失败,因为您认为您的提交不起作用。尝试调试您的验证并将以下行放在 findFormErrors 函数中并提供反馈:

const { firstName, lastName, email, city, company, howCanWeHelp, NDA } = form;   

代码:

const Contact = () => {
  const [files, setFiles] = useState(null);
  const [successful, setSuccessful] = useState(false);
  const [form, setForm] = useState({});
  const [errors, setErrors] = useState({});

  const setField = (field, value) => {
    setForm({
      ...form,
      [field]: value,
    });

    if (!!errors[field])
      setErrors({
        ...errors,
        [field]: null,
      });
  };

 

  const findFormErrors = () => {
     const { firstName, lastName, email, city, company, howCanWeHelp, NDA } = form; // place it here
    const newErrors = {};

    if (!firstName || firstName === "") newErrors.firstName = "cannot be blank";
    if (!lastName || lastName === "") newErrors.lastName = "cannot be blank";
    if (!email || !email.includes("@")) newErrors.email = "enter a valid email";
    if (!company || company === "") newErrors.company = "cannot be blank";
    if (!howCanWeHelp || howCanWeHelp === "")
      newErrors.howCanWeHelp = "cannot be blank";

    return newErrors;
  };

  const onFileUpload = async (e) => {
    setFiles(e.target.files[0]);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();

    const newErrors = findFormErrors();

    if (Object.keys(newErrors).length > 0) {
      setErrors(newErrors);
    } else {
      const formData = new FormData();
      formData.append("firstName", firstName);
      formData.append("lastName", lastName);
      formData.append("email", email);
      formData.append("city", city);
      formData.append("company", company);
      formData.append("howCanWeHelp", howCanWeHelp);
      formData.append("NDA", NDA);
      formData.append("file", files);

      const companyForm = `${process.env.REACT_APP_PUBLIC_REQUEST}/company-form`;

      await Axios.post(companyForm, formData, {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      })
        .then(() => {
          setSuccessful(true);
        })
        .catch((error) => console.error(error));
    }
  };

  return (
    <div className={`${styles.container}`}>
      <Form onSubmit={handleSubmit}>
        <Row className={styles["contact__row"]}>
          <Col className={styles["contact__form-content"]}>
            <h2>Contact Us</h2>

            <Form.Group className="mb-3">
              <Form.Label>First Name*</Form.Label>
              <Form.Control
                onChange={(e) => setField("firstName", e.target.value)}
                type="text"
                isInvalid={!!errors.firstName}
              />
              <Form.Control.Feedback type="invalid">
                {errors.firstName}
              </Form.Control.Feedback>
            </Form.Group>

            <Form.Group className="mb-3">
              <Form.Label>Last Name*</Form.Label>
              <Form.Control
                onChange={(e) => setField("lastName", e.target.value)}
                type="text"
                isInvalid={!!errors.lastName}
              />
              <Form.Control.Feedback type="invalid">
                {errors.lastName}
              </Form.Control.Feedback>
            </Form.Group>

            <Form.Group className="mb-3">
              <Form.Label>Email*</Form.Label>
              <Form.Control
                onChange={(e) => setField("email", e.target.value)}
                type="text"
                isInvalid={!!errors.email}
              />
              <Form.Control.Feedback type="invalid">
                {errors.email}
              </Form.Control.Feedback>
            </Form.Group>

            <Form.Group className="mb-3">
              <Form.Label>City:</Form.Label>
              <Form.Control
                onChange={(e) => setField("city", e.target.value)}
                type="text"
              />
            </Form.Group>

            <Form.Group className="mb-3">
              <Form.Label>Company:</Form.Label>
              <Form.Control
                onChange={(e) => setField("company", e.target.value)}
                type="text"
                isInvalid={!!errors.company}
              />
              <Form.Control.Feedback type="invalid">
                {errors.company}
              </Form.Control.Feedback>
            </Form.Group>

            <Form.Group className="mb-3">
              <Form.Label>How we can help you?*</Form.Label>
              <Form.Control
                onChange={(e) => setField("howCanWeHelp", e.target.value)}
                as="textarea"
                row={4}
                isInvalid={!!errors.howCanWeHelp}
              />
              <Form.Control.Feedback type="invalid">
                {errors.howCanWeHelp}
              </Form.Control.Feedback>
            </Form.Group>

            <Form.Group className="mb-3">
              <Form.Label>Attach your files here:</Form.Label>
              <Form.Control onChange={onFileUpload} type="file" />
            </Form.Group>

            <div className={styles["contact__button-checkbox"]}>
              <Form.Group className="mb-3">
                <Form.Check
                  defaultChecked={NDA}
                  onChange={(e) => {
                    setField("NDA", e.target.checked);
                  }}
                  type="checkbox"
                  label="Send NDA"
                />
              </Form.Group>
              <Button
                disabled={successful}
                type="submit"
                variant="outline-dark"
              >
                {successful ? "Sent Successfully" : "SEND"}
              </Button>
            </div>
          </Col>

As you are validation on every submit clicked so it might be possible that some of your validation fails due to which you feel that your submit is not working.Try to debug your validations and place the line following line in the findFormErrors function and provide feedback:

const { firstName, lastName, email, city, company, howCanWeHelp, NDA } = form;   

Code:

const Contact = () => {
  const [files, setFiles] = useState(null);
  const [successful, setSuccessful] = useState(false);
  const [form, setForm] = useState({});
  const [errors, setErrors] = useState({});

  const setField = (field, value) => {
    setForm({
      ...form,
      [field]: value,
    });

    if (!!errors[field])
      setErrors({
        ...errors,
        [field]: null,
      });
  };

 

  const findFormErrors = () => {
     const { firstName, lastName, email, city, company, howCanWeHelp, NDA } = form; // place it here
    const newErrors = {};

    if (!firstName || firstName === "") newErrors.firstName = "cannot be blank";
    if (!lastName || lastName === "") newErrors.lastName = "cannot be blank";
    if (!email || !email.includes("@")) newErrors.email = "enter a valid email";
    if (!company || company === "") newErrors.company = "cannot be blank";
    if (!howCanWeHelp || howCanWeHelp === "")
      newErrors.howCanWeHelp = "cannot be blank";

    return newErrors;
  };

  const onFileUpload = async (e) => {
    setFiles(e.target.files[0]);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();

    const newErrors = findFormErrors();

    if (Object.keys(newErrors).length > 0) {
      setErrors(newErrors);
    } else {
      const formData = new FormData();
      formData.append("firstName", firstName);
      formData.append("lastName", lastName);
      formData.append("email", email);
      formData.append("city", city);
      formData.append("company", company);
      formData.append("howCanWeHelp", howCanWeHelp);
      formData.append("NDA", NDA);
      formData.append("file", files);

      const companyForm = `${process.env.REACT_APP_PUBLIC_REQUEST}/company-form`;

      await Axios.post(companyForm, formData, {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      })
        .then(() => {
          setSuccessful(true);
        })
        .catch((error) => console.error(error));
    }
  };

  return (
    <div className={`${styles.container}`}>
      <Form onSubmit={handleSubmit}>
        <Row className={styles["contact__row"]}>
          <Col className={styles["contact__form-content"]}>
            <h2>Contact Us</h2>

            <Form.Group className="mb-3">
              <Form.Label>First Name*</Form.Label>
              <Form.Control
                onChange={(e) => setField("firstName", e.target.value)}
                type="text"
                isInvalid={!!errors.firstName}
              />
              <Form.Control.Feedback type="invalid">
                {errors.firstName}
              </Form.Control.Feedback>
            </Form.Group>

            <Form.Group className="mb-3">
              <Form.Label>Last Name*</Form.Label>
              <Form.Control
                onChange={(e) => setField("lastName", e.target.value)}
                type="text"
                isInvalid={!!errors.lastName}
              />
              <Form.Control.Feedback type="invalid">
                {errors.lastName}
              </Form.Control.Feedback>
            </Form.Group>

            <Form.Group className="mb-3">
              <Form.Label>Email*</Form.Label>
              <Form.Control
                onChange={(e) => setField("email", e.target.value)}
                type="text"
                isInvalid={!!errors.email}
              />
              <Form.Control.Feedback type="invalid">
                {errors.email}
              </Form.Control.Feedback>
            </Form.Group>

            <Form.Group className="mb-3">
              <Form.Label>City:</Form.Label>
              <Form.Control
                onChange={(e) => setField("city", e.target.value)}
                type="text"
              />
            </Form.Group>

            <Form.Group className="mb-3">
              <Form.Label>Company:</Form.Label>
              <Form.Control
                onChange={(e) => setField("company", e.target.value)}
                type="text"
                isInvalid={!!errors.company}
              />
              <Form.Control.Feedback type="invalid">
                {errors.company}
              </Form.Control.Feedback>
            </Form.Group>

            <Form.Group className="mb-3">
              <Form.Label>How we can help you?*</Form.Label>
              <Form.Control
                onChange={(e) => setField("howCanWeHelp", e.target.value)}
                as="textarea"
                row={4}
                isInvalid={!!errors.howCanWeHelp}
              />
              <Form.Control.Feedback type="invalid">
                {errors.howCanWeHelp}
              </Form.Control.Feedback>
            </Form.Group>

            <Form.Group className="mb-3">
              <Form.Label>Attach your files here:</Form.Label>
              <Form.Control onChange={onFileUpload} type="file" />
            </Form.Group>

            <div className={styles["contact__button-checkbox"]}>
              <Form.Group className="mb-3">
                <Form.Check
                  defaultChecked={NDA}
                  onChange={(e) => {
                    setField("NDA", e.target.checked);
                  }}
                  type="checkbox"
                  label="Send NDA"
                />
              </Form.Group>
              <Button
                disabled={successful}
                type="submit"
                variant="outline-dark"
              >
                {successful ? "Sent Successfully" : "SEND"}
              </Button>
            </div>
          </Col>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文