Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Form Validation in Multi step form

I have a multi step that has an input validation. Instead of displaying a toast for the empty input error, I want to show an error text under the input field. Just like this:

enter image description here

Apparently it’s not good practice to use a toast message for these kind of errors.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const [formData, setFormData] = useState({
    businessName: "",
    businessEmail: "",
    currency: "",
    industry: "",
    businessDescription: "",
    useCase: "",
    organisationType: "",
    website: "",
    businessPhone: "",
    country: "",
    billingName: "",
    billingEmail: "",
    addressState: "",
    addressCity: "",
    addressStreet: "",
  });
const handleSubmit = () => {
    if (step === 0) {
      if (formData.businessName === "") {
        toast({
          title: "Error",
          description: "Please provide a business name",
          status: "error",
          position: "top-right",
          duration: 3000,
          isClosable: true,
        });
      }
      if (formData.businessEmail === "") {
        toast({
          title: "Error",
          description: "Please provide a business email",
          status: "error",
          position: "top-right",
          duration: 3000,
          isClosable: true,
        });
      } else {
        setStep(step + 1);
      }
    } else if (step === 1) {
      if (formData.website === "") {
        toast({
          title: "Error",
          description: "Please provide a website",
          status: "error",
          position: "top-right",
          duration: 3000,
          isClosable: true,
        });
      }
      if (formData.businessPhone === "") {
        toast({
          title: "Error",
          description: "Please provide a registered phone number",
          status: "error",
          position: "top-right",
          duration: 3000,
          isClosable: true,
        });
      } else {
        setStep(step + 1);
      }
    } else if (step === 2) { ............. and so on.

This is my form in one of the steps:

export default function Account({ formData, setFormData }) {

return (
  <Input
     placeholder="Business Name"
     name="businessName"
     onChange={(e) => {
     setFormData({
      ...formData,
      businessName: e.target.value,
     });
     }}
     value={formData.businessName}
     type="name"
  />

<Input
     placeholder="Business Email"
     name="businessEmail"
     onChange={(e) => {
     setFormData({
      ...formData,
      businessEmail: e.target.value,
     });
     }}
     value={formData.businessEmail}
     type="email"
  />

......... and so on.
)

>Solution :

your form and state management logic will be as follows

Add an error state to track the presence of errors for each input field:

const [errors, setErrors] = useState({
  businessName: "",
  businessEmail: "",
  // Add error states for other fields
});

Update the handleSubmit function to set the errors instead of showing toasts:

    const handleSubmit = () => {
      let formErrors = {};
    
      if (step === 0) {
        if (formData.businessName === "") {
          formErrors.businessName = "Please provide a business name";
        }
    
        if (formData.businessEmail === "") {
          formErrors.businessEmail = "Please provide a business email";
        }
      } else if (step === 1) {
        if (formData.website === "") {
          formErrors.website = "Please provide a website";
        }
    
        if (formData.businessPhone === "") {
          formErrors.businessPhone = "Please provide a registered phone number";
        }
      }
    
      if (Object.keys(formErrors).length > 0) {
        setErrors(formErrors);
      } else {
        setErrors({});
        setStep(step + 1);
      }
    };

Modify your form component to display the error text:

export default function Account({ formData, setFormData, errors }) {
  return (
    <>
      <Input
        placeholder="Business Name"
        name="businessName"
        onChange={(e) => {
          setFormData({
            ...formData,
            businessName: e.target.value,
          });
        }}
        value={formData.businessName}
        type="name"
      />
      {errors.businessName && <Text color="red">{errors.businessName}</Text>}

      <Input
        placeholder="Business Email"
        name="businessEmail"
        onChange={(e) => {
          setFormData({
            ...formData,
            businessEmail: e.target.value,
          });
        }}
        value={formData.businessEmail}
        type="email"
      />
      {errors.businessEmail && <Text color="red">{errors.businessEmail}</Text>}

      {/* Render other input fields and error texts */}
    </>
  );
}

Now, when an error occurs, it will be stored in the errors state for the corresponding field. The error text will be displayed below the input field, indicated by the red color. Once the errors are resolved and the form is submitted without any errors, the errors state will be cleared, and the form can proceed to the next step.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading