Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yup and useForm validation errors does not trigger when contact is form is empty

I am using react-hooks and yup for my contact form. I have added my yup schema as expected and error boundaries but they don't trigger when I try to submit it with empty fields. The empty form goes straight to the database which I don't want. Why is it not triggering?

My contact form code is as follows:

import { useForm } from "react-hook-form";
import * as yup from "yup";
import { yupResolver } from "@hookform/resolvers/yup";
import { ErrorMessage } from "@hookform/error-message";
 
const schema = yup.object().shape({
  fullName: yup.string().required("Please enter your full name"),
  email: yup.string().required("Please enter your email"),
  select: yup
    .string()
    .oneOf(["webSolutions", "mobileSolutions", "devOps", "research", "uiux"])
    .required("Please choose one of our services"),
  message: yup.string().required("Message can not be left blank"),
});

const Contact = () => {
  const [fullName, setFullName] = useState("");
  const [email, setEmail] = useState("");
  const [message, setMessage] = useState("");
  const [selecttype , setSelectType ] = useState([]);

 
  const {
    formState: { errors },
  } = useForm({
    resolver: yupResolver(schema),
  });

  const handleSubmit = (e) => {
    e.preventDefault();
    db.collection("contacts")
      .add({
        fullName: fullName,
        email: email,
        selecttype : selecttype ,
        message: message,
      })
      .then(() => {
        alert("message has been submitted");
      })
      .catch((error) => {
        alert(error.message);
      });
  setFullName("");
  setEmail("");
  setMessage("");
  setSelectType("");
  };

  return (
    <>
      <Container>
        <FormBg>
          <ImageBg>
            <Img src={Image} />
          </ImageBg>
        </FormBg>
        <FormWrap>
          <FormContent>
            <Form onSubmit={handleSubmit}>
              <Icon to="/">
                <img src={dLogo} />
              </Icon>
              <FormH1>Fill in your request details below</FormH1>
              <FormLabel value="fullName">
                Full Name <RequiredTag>*</RequiredTag>
              </FormLabel>
              <FormInput
                type="text"
                name="fullName"
                onChange={(e) => setFullName(e.target.value)}
              />
              <ErrorTag>
                <ErrorMessage errors={errors} name="fullName" />
              </ErrorTag>

              <FormLabel value="email">
                Email <RequiredTag>*</RequiredTag>
              </FormLabel>
              <FormInput
                type="email"
                name="email"
                placeholder="[email protected]"
                onChange={(e) => setEmail(e.target.value)}
              />
              <ErrorTag>
                <ErrorMessage errors={errors} name="email" />
              </ErrorTag>
              <FormLabel value="services">
                What would you wants to do for you?
                <RequiredTag>*</RequiredTag>
              </FormLabel>
              <select
                onChange={(e) => {
                  const selectedOption = e.target.value;
                  setSelectType (selectedOption);
                  console.log(selectedOption);
                }}
              >
                <option>Select ...</option>
                <option value="webSolutions">Web Solutions</option>
                <option value="mobileSolutions">Mobile Solutions</option>
                <option value="devOps">DevOps Solutions</option>
                <option value="research">Research Assistance</option>
                <option value="uiux">UI/UX Design</option>
              </select>
            
              <ErrorTag>
                <ErrorMessage errors={errors} name="select" />
              </ErrorTag>
              <FormLabel value="message">
                Message <RequiredTag>*</RequiredTag>
              </FormLabel>
              <textarea
                name="message"
                placeholder="Tell us more about your request like bugdets, questions and more"
                onChange={(e) => setMessage(e.target.value)}
              />
              <ErrorTag>
                <ErrorMessage errors={errors} name="message" />
              </ErrorTag>
              <FormButton type="submit">Submit Request</FormButton>
              <Text>We respond within 48 hours😉</Text>
            </Form>
          </FormContent>
        </FormWrap>
      </Container>
    </>
  );
};

export default Contact;```
like image 599
Soloh Avatar asked Dec 10 '25 18:12

Soloh


1 Answers

You can also set .required() on your yup.object().shape({...}) which will make sure that the object will not be empty when validating.

It will look like this:

const schema = yup.object().shape({
  // Your shape fields
}).required(); // -> here is where you add it

Edit

You are also not using React Hook Form's submit wrapper, this is probably why the form gets submit even though there are errors.

const { handleSubmit } = useForm();

const yourSubmitHandler = () => {
  // ...
};

return (
  <Form onSubmit={handleSubmit(yourSubmitHandler)}>
    {/* Rest of the form  */}
  </Form>
);
like image 63
AC3 Avatar answered Dec 12 '25 08:12

AC3



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!