在NextJS中提交表单数据后验证并显示成功消息

发布于 2025-02-13 13:48:26 字数 1359 浏览 0 评论 0原文

我希望你做得好。我看上去迷路了,试图解决此代码。因此,我在NextJS应用程序中有一个表单组件,并且正在尝试验证并在表单上显示成功或错误消息。如果您也需要,这是代码和CSS。

JSX代码:

import { useRef } from "react";

export default function Form() {
  const nameRef = useRef();
  const emailRef = useRef();
  const purposeRef = useRef();
  const portfolioRef = useRef();
  const messageRef = useRef();
  const locationRef = useRef();
  const comradeRef = useRef();

  function submitHandler(event) {
    event.preventDefault();

    const enteredName = nameRef.current.value;
    const enteredEmail = emailRef.current.value;
    const enteredPurpose = purposeRef.current.value;
    const enteredPortfolio = portfolioRef.current.value;
    const enteredMessage = messageRef.current.value;
    const enteredLocation = locationRef.current.value;
    const enteredComrade = comradeRef.current.value;

    const reqBody = {
      name: enteredName,
      email: enteredEmail,
      purpose: enteredPurpose,
      portfolio: enteredPortfolio,
      message: enteredMessage,
      location: enteredLocation,
      comrade: enteredComrade,
    };

    fetch("/api/feedback", {
      method: "POST",
      body: JSON.stringify(reqBody),
      headers: {
        "Content-Type": "application/json",
      },
    })
      .then((response) => response.json())
      .then((data) => console.log(data));

    // 
              

there I hope you are doing good. I look lost and stupid trying to solve this code. So I have a form component in my NextJs app and I am trying to validate and display either a successful or error message onSubmit on the form. here is the code and the CSS if you need it too.

JSX CODE:

import { useRef } from "react";

export default function Form() {
  const nameRef = useRef();
  const emailRef = useRef();
  const purposeRef = useRef();
  const portfolioRef = useRef();
  const messageRef = useRef();
  const locationRef = useRef();
  const comradeRef = useRef();

  function submitHandler(event) {
    event.preventDefault();

    const enteredName = nameRef.current.value;
    const enteredEmail = emailRef.current.value;
    const enteredPurpose = purposeRef.current.value;
    const enteredPortfolio = portfolioRef.current.value;
    const enteredMessage = messageRef.current.value;
    const enteredLocation = locationRef.current.value;
    const enteredComrade = comradeRef.current.value;

    const reqBody = {
      name: enteredName,
      email: enteredEmail,
      purpose: enteredPurpose,
      portfolio: enteredPortfolio,
      message: enteredMessage,
      location: enteredLocation,
      comrade: enteredComrade,
    };

    fetch("/api/feedback", {
      method: "POST",
      body: JSON.stringify(reqBody),
      headers: {
        "Content-Type": "application/json",
      },
    })
      .then((response) => response.json())
      .then((data) => console.log(data));

    // ????️ clear all input values in the form
    event.target.reset();
  }

  return (
    <div className={classes.divForm}>
      <form onSubmit={submitHandler}>
        <div className={classes.formInputDiv}>
          <div className={classes.label}>
            <label htmlFor="name">
              What Do We Call You?:
              <span
                style={{
                  color: "blue",
                  fontSize: "0.65rem",
                  float: "right",
                }}
              >
                *Required
              </span>
            </label>
          </div>
          <input
            required
            className={classes.input}
            type="text"
            id="name"
            name="name"
            placeholder="Enter Your Name"
            ref={nameRef}
          />
        </div>

        <div className={classes.formInputDiv}>
          <div className={classes.label}>
            <label htmlFor="email">
              Your Email Address:
              <span
                style={{
                  color: "blue",
                  fontSize: "0.65rem",
                  float: "right",
                }}
              >
                *Required
              </span>
            </label>
          </div>
          <input
            required
            className={classes.input}
            type="email"
            id="email"
            name="email"
            placeholder="Enter Your Email Address"
            ref={emailRef}
          />
        </div>

        <div className={classes.formInputDiv}>
          <div className={classes.label}>
            <label htmlFor="purpose">
              Purpose Of Contact:
              <span
                style={{
                  color: "blue",
                  fontSize: "0.65rem",
                  float: "right",
                }}
              >
                *Required
              </span>
            </label>
          </div>
          <select
            style={{
              background: "#EFF0F5",
              fontSize: "0.85rem",
              padding: "0 1rem",
              fontFamily: "'Source Sans Pro', sans-serif",
            }}
            id="purpose"
            name="purpose"
            className={classes.input}
            required
            ref={purposeRef}
          >
            <option value="General Inquiries">General Inquiries</option>
            <option value="Work / Collaboration">Work / Collaboration</option>
            <option value="Endorsement / Partnership">
              Endorsement / Partnership
            </option>
            <option value="Quotes / Pricing">Quotes / Project Plan</option>
          </select>
        </div>

        <div className={classes.formInputDiv}>
          <div className={classes.label}>
            <label htmlFor="message">
              Drop Message:
              <span
                style={{
                  color: "blue",
                  fontSize: "0.65rem",
                  float: "right",
                }}
              >
                *Required
              </span>
            </label>
          </div>
          <textarea
            className={classes.textarea}
            type="text"
            rows="5"
            cols="50"
            id="message"
            name="message"
            placeholder="Give us the full gist. Tell us Wassup!"
            required
            ref={messageRef}
          />
        </div>

        <div className={classes.formInputDiv}>
          <div className={classes.label}>
            <label htmlFor="portfolio">Link To Portfolio (Optional):</label>
          </div>
          <input
            className={classes.input}
            type="text"
            id="portfolio"
            name="portfolio"
            placeholder="Enter a link to your portoflio"
            ref={portfolioRef}
          />
        </div>

        <div className={classes.formRow}>
          <div className={classes.formColumn}>
            <div className={classes.label}>
              <label htmlFor="location">
                Your Location:
                <span
                  style={{
                    color: "blue",
                    fontSize: "0.65rem",
                    float: "right",
                  }}
                >
                  *Required
                </span>
              </label>
            </div>
            <input
              required
              className={classes.input}
              type="text"
              id="location"
              name="plocation"
              placeholder="Where Are You Based?"
              ref={locationRef}
            />
          </div>
          <div className={classes.formColumn}>
            <div className={classes.label}>
              <label htmlFor="comrade">
                Hodl A Comrade?:
                <span
                  style={{
                    color: "blue",
                    fontSize: "0.65rem",
                    float: "right",
                  }}
                >
                  *Required
                </span>
              </label>
            </div>
            <input
              required
              className={classes.input}
              type="text"
              id="comrade"
              name="comrade"
              placeholder="Enter Yes or No"
              ref={comradeRef}
            />
          </div>
        </div>

        <div className={classes.buttonDiv}>
          <button className={classes.formButton} type="submit">
            Submit
          </button>
        </div>
      </form>
    </div>
  );
}

I need help on how to achieve this, I know it's not much of a big deal, but someone should help out. Pardon the long code, as this is my first major project using React and NextJs FrameWork.

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

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

发布评论

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

评论(2

自此以后,行同陌路 2025-02-20 13:48:26

您可能想跟踪表单错误状态:

ex:

  const nameRef = useRef();
const emailRef = useRef();
const purposeRef = useRef();
const portfolioRef = useRef();
const messageRef = useRef();
const locationRef = useRef();
const comradeRef = useRef();

const [isError, setIsError] = useState(null);

function submitHandler(event) {
event.preventDefault();

const enteredName = nameRef.current.value;
const enteredEmail = emailRef.current.value;
const enteredPurpose = purposeRef.current.value;
const enteredPortfolio = portfolioRef.current.value;
const enteredMessage = messageRef.current.value;
const enteredLocation = locationRef.current.value;
const enteredComrade = comradeRef.current.value;

const reqBody = {
name: enteredName,
email: enteredEmail,
purpose: enteredPurpose,
portfolio: enteredPortfolio,
message: enteredMessage,
location: enteredLocation,
comrade: enteredComrade,
};

fetch("/api/feedback", {
method: "POST",
body: JSON.stringify(reqBody),
headers: {
"Content-Type": "application/json",
},
})
.then((response) => {
console.log(response);
setIsError(false); // <-- Here
})
.catch(() => setIsError(true)); // <-- and here

//

You probably want to keep track of the form error status:

Ex:

  const nameRef = useRef();
  const emailRef = useRef();
  const purposeRef = useRef();
  const portfolioRef = useRef();
  const messageRef = useRef();
  const locationRef = useRef();
  const comradeRef = useRef();

  const [isError, setIsError] = useState(null);

  function submitHandler(event) {
    event.preventDefault();

    const enteredName = nameRef.current.value;
    const enteredEmail = emailRef.current.value;
    const enteredPurpose = purposeRef.current.value;
    const enteredPortfolio = portfolioRef.current.value;
    const enteredMessage = messageRef.current.value;
    const enteredLocation = locationRef.current.value;
    const enteredComrade = comradeRef.current.value;

    const reqBody = {
      name: enteredName,
      email: enteredEmail,
      purpose: enteredPurpose,
      portfolio: enteredPortfolio,
      message: enteredMessage,
      location: enteredLocation,
      comrade: enteredComrade,
    };

    fetch("/api/feedback", {
      method: "POST",
      body: JSON.stringify(reqBody),
      headers: {
        "Content-Type": "application/json",
      },
    })
      .then((response) => {
        console.log(response);
        setIsError(false); // <-- Here
      })
      .catch(() => setIsError(true)); // <-- and here

    // ????️ clear all input values in the form
    event.target.reset();
  }

And then render the message based on whether this is an error or not:

...
   <div className={classes.buttonDiv}>
      <button className={classes.formButton} type="submit">
         Submit
      </button>
   </div>
   { isError === true && (<div>Error!</div>) }
   { isError === false && (<div>Success!</div>) }
...
寄居人 2025-02-20 13:48:26

作为您的第一个主要项目,您在其中做得很好。我会说使用 react to toastify 库。它易于使用。您的代码看起来有点像这样:

import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";

...
...

fetch("/api/feedback", {
  method: "POST",

  body: JSON.stringify(reqBody),

  headers: {
"Content-Type": "application/json"
  },

})

  .then((response) => response.json())

  .then((data) => {console.log(data) ; toast.success(data.message)});
  .catch((error) => toast.error(data.message));

... ...

<ToastContainer />

You are doing good in it as your first major project. I would say use react-toastify library . Its easy to use. Your code would look a bit like this :

import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";

...
...

fetch("/api/feedback", {
  method: "POST",

  body: JSON.stringify(reqBody),

  headers: {
"Content-Type": "application/json"
  },

})

  .then((response) => response.json())

  .then((data) => {console.log(data) ; toast.success(data.message)});
  .catch((error) => toast.error(data.message));

...

<ToastContainer />
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文