PazzeG
PazzeG

Reputation: 137

Prevent to send form if there is an error

A sandbox with my components : https://codesandbox.io/s/fancy-star-7gite

Hello, I've tried to code in React.js a contact form which check if values of inputs are good and send it to a mailbox via email.js. Sample of the validation's file(validateInfo.jsx):

    if(!values.email) {  
        errors.email= "Enter an e-mail";
    } else if (!/\S+@\S+\.\S+/.test(values.email)){
        errors.email= "Enter a valid email";
    }

But at the submission of the form even if the values are wrong, it sends the form. I want to prevent it.

To transport the form to a mailbox I've created a hook to manage the sending of the information in the form (useContact.jsx):

import {useState, useEffect} from 'react'
import emailjs from "emailjs-com";
import  {template}  from "./template";
import  {userId}  from "./userid";

export const useContact = (callback, validate) => {
    const [values, setValues] = useState({
        email:'',
        emailConf:'',
        userName:'',
        phone:'',
    })
    const [errors, setErrors] = useState({})
    const [isSubmitting, setIsSubmitting] = useState(false)
    
    const handleChange = e =>{
        const {name, value}= e.target
        setValues({
            ...values,
            [name]: value
        })
    }

    function handleSubmit(e) {
        e.preventDefault() 

        setIsSubmitting(true)
        setErrors(validate(values))
            emailjs.sendForm('gmail', template, e.target, userId)
            .then((result) => {
                console.log(result)
            }, (errors) => {
                console.log(errors);
            });

        e.target.reset();
        localStorage.clear();   
    }
    useEffect(() =>{
        if(Object.keys(errors).length === 0 && isSubmitting)
        {
            callback();
        }
    },[errors])

    return {handleChange, handleSubmit, values, errors};
}

The form (ContactInfo.jsx):

import './Contact.css';
import { useContact } from "./useContact";
import validate from './validateInfo';

export default function ContactInfo({submitForm}) {


    const {handleChange, values, handleSubmit, errors}
    = useContact(
        submitForm,
        validate
    )
   
  return (<> 
    <div className="contact-container">

      <div className="contactForm" >

        <form className="Contact" onSubmit={handleSubmit} >
    
          <input 
          id="email" 
          name="email" 
          type="email" 
          value={values.email}
          onChange={handleChange}
          className="form-input" 
          placeholder="E-mail"  
          minLength= '5' 
          maxLength ='50' 
          autoComplete="off"/>
         {errors.email && <p> {errors.email} </p>}
         
          <input 
          name="emailConf" 
          id="emailConf" 
          type="email" 
          value={values.emailConf}
          onChange={handleChange}
          className="form-input" 
          minLength= '5' 
          maxLength='50' 
          autoComplete="off"
          placeholder="E-mail confirmation"/>
         {errors.emailConf && <p> {errors.emailConf} </p>}

          
          <input 
          name="userName" 
          id="userName"
          value={values.userName}
          onChange={handleChange} 
          className="form-input" 
          maxLength='50' 
          autoComplete="off"
          placeholder="Name"/>

          <input 
          name="phone" 
          id="phone" 
          type="tel"
          value={values.phone}
          onChange={handleChange}
          className="form-input"
          maxLength='10' 
          autoComplete="off"
          placeholder="Phone Number"/>
         {errors.phone && <p> {errors.phone} </p>}

          
          <textarea 
          className="message" 
          name="message" 
          maxLength='500' 
          placeholder="Write your message here..." />
          
          <button className="submit-Btn" type="submit">
          Send
          </button>

           
        </form>

      </div>
    
    </div>
    </>
  );
}

Thank you for helping me if you want more informations tell me =).

Upvotes: 0

Views: 281

Answers (1)

RABI
RABI

Reputation: 732

You are missing a condition in submit method. You are not validating whether there is any error in validation. It should be as follows. Updated the codesandbox as well

function handleSubmit(e) {
    e.preventDefault();

    setIsSubmitting(true);
    setErrors(validate(values));
    if (validate(values) === {}) {
      emailjs.sendForm("gmail", template, e.target, userId).then(
        (result) => {
          console.log(result);
        },
        (errors) => {
          console.log(errors);
        }
      );

      e.target.reset();
      localStorage.clear();
    }
  }

Upvotes: 1

Related Questions