How do you add a condition for invalid/empty input to a Contact Form using FormSpree?

Viewed 27

I am using Formspree to make a simple Contact form in my NextJS website. Formspree provides the following sample code snippet for React:

// Make sure to run npm install @formspree/react
// For more help visit https://formspr.ee/react-help
import React from 'react';
import { useForm, ValidationError } from '@formspree/react';
function ContactForm() {
  const [state, handleSubmit] = useForm("YOUR_FORMSPREE_UNIQUE_KEY");
  if (state.succeeded) {
      return <p>Thanks for joining!</p>;
  }
  return (
      <form onSubmit={handleSubmit}>
      <label htmlFor="email">
        Email Address
      </label>
      <input
        id="email"
        type="email" 
        name="email"
      />
      <ValidationError 
        prefix="Email" 
        field="email"
        errors={state.errors}
      />
      <textarea
        id="message"
        name="message"
      />
      <ValidationError 
        prefix="Message" 
        field="message"
        errors={state.errors}
      />
      <button type="submit" disabled={state.submitting}>
        Submit
      </button>
    </form>
  );
}
function App() {
  return (
    <ContactForm />
  );
}
export default App;

Trouble is, if a user submits the form with empty fields, it still gets submitted. I searched the web, looked up some formspree implementations on YT and checked their website. But didn't find a solution on how to prevent a user from submitting with empty fields.

1 Answers

I implemented the simplest solution I could think of:

  1. I modified the onSubmit of the form in the following way, adding a switch statement:

    onSubmit = { (email.length>0 && message.length > 0) ? handleSubmit : errorAlert}
  2. Added errorAlert function as follows:

    function errorAlert() { alert("cannot leave any field blank.") }

This way, using a switch statement one can add whatever conditions and failsafes one wishes to add to the form submission text fields.

Related