在获取 API 和重定向页面之前反应 JS 表单验证

React JS Form Validation Before Fetching an API and Redirecting Page

我有一个独特的 React Js 表单,我想在提交前验证它。

问题是我的 onClick 函数正在执行另外两个进程。

我正在获取数据并重定向。我正在尝试在两个进程中的任何一个采取行动之前验证 phone。

phone/email/name 字段不应为空,如果为空,则抓取或重定向不得执行操作。

默认情况下,号码以 +27 开头。

我试过的方法,Joi FormReact-Form-Hoodstatement

代码如下:

import React, { useState } from "react";
import { useNavigate } from "react-router-dom";
import Page from "react-page-loading";


function Checkout({ cart, setResponse }) {
  const [contactPreference, setContactPreference] = useState("");
  const [name, setName] = useState("");
  const [phone, setPhone] = useState("");
  const [email, setEmail] = useState("");
  const navigate = useNavigate();
  const [spinner, setSpinner] = useState(false);

  const handleSubmit = async () => {
    setSpinner(true);
    const token = "2c506c6b-d880-36bb-bdba-a035d1464b35";
    const data = {
      transactionReference: "string",
      paymentMethod: "CreditCard",
      checkoutOrderUrl: "http://www.test.com/",
      user: {
        name: name,
        msisdn: "+27" + phone,
        email: email,
      },
      payementMethodDetail: {
        RedirectUrl: "http://localhost:3000/",
        PurchaseEventWebhookUrl: "http://www.test.com",
      },

      bundle: cart.map((item) => ({
        ProductCode: `${item.ProductCode}`,
        Amount: item.amount,
        CurrencyCode: item.currencyCode,
        Quantity: item.quantity,
      })),
    };
    const requestOptions = {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${token}`,
      },
      body: JSON.stringify(data),
    };
    await fetch(
      "https://api.flash-internal.flash-group.com/ecommerceManagement/1.0.0/api/checkout/",
      requestOptions
    )
      .then((response) => response.json())
      .then((response) => {
        setResponse(response);
      })
      .then(() => {
        setSpinner(false);
        navigate("/payment");
      });
  };

  console.log();

  return (
    <div className="App">
      <div>
        Name: <input onChange={(event) => setName(event.target.value)} />
        <form className="form-inline">
          <label className="my-1 mr-2" for="inlineFormCustomSelectPref">
            How should we contact you ??
          </label>
          <select
            onChange={(e) => {
              setContactPreference(e.target.value);
            }}
            className="custom-select my-1 mr-sm-2"
            id="inlineFormCustomSelectPref"
          >
            <option selected>Choose...</option>
            <option value="phone">Phone Number</option>
            <option value="email">Email</option>
          </select>
          {contactPreference === "phone" ? (
            <input
              placeholder="+27"
              onChange={(event) => setPhone(event.target.value)}
            />
          ) : contactPreference === "email" ? (
            <input
              placeholder="Email"
              onChange={(event) => setEmail(event.target.value)}
            />
          ) : (
            <></>
          )}
        </form>
      </div>
      <button type="submit" onClick={handleSubmit}>
        Proceed to Payment
      </button>
      {spinner && <Page loader={"spin"} color={"#b2fa00"} size={4}></Page>}
    </div>
  );
}

export default Checkout;

您可以将 required 属性添加到 input 和 select 元素,将 ref 放在表单元素上,然后在您的 handleSubmit 函数中,使用

const formValid = formRef.current?.reportValidity()

获取布尔结果并让浏览器显示缺失字段的提示。