Home > Mobile >  Value type error message displaying instead of required error message on empty input submission
Value type error message displaying instead of required error message on empty input submission

Time:10-06

I'm using react-hook-form and yup together and for some reason it's displaying the wrong error message.

When the phone number input is left empty on submitting the form, it displays the typeError error message instead of the 'required' error message which I can't understand why that's happening since the input field is blank and there's no value to determine that it's of type 'number' or not.

import { yupResolver } from "@hookform/resolvers/yup";
import { useForm } from "react-hook-form";
import * as yup from "yup";

const schema = yup.object().shape({
  name: yup.string().required("Field is required*"),
  email: yup.string().email().required("Field is required*"),
  phoneNumber: yup
    .number()
    .required("Field is required*") //this message should be displayed instead of typeError message
    .typeError("Value must be a number*"),
  message: yup.string().required("Please provide your message*")
});


export default function App() {
  const {
    reset,
    register,
    handleSubmit,
    formState: { errors }
  } = useForm({ resolver: yupResolver(schema) });

  const submitForm = (data) => {
    console.log(data);
    reset();
  };


  return (
    <div className="App">
               <form className="contact-form" onSubmit={handleSubmit(submitForm)}>
            <h2>Send Us a Message </h2>
            <p>
              <label for="name">Name</label>
              <input name="name" type="text" {...register("name")} />
              <p className="error-msg"> {errors.name?.message} </p>
            </p>

            <p>
              <label for="email">Email</label>
              <input name="email" type="text" {...register("email")} />
              <p className="error-msg"> {errors.email?.message} </p>
            </p>

            <p>
              <label for="phoneNumber">Phone</label>
              <input
                name="phoneNumber"
                type="text"
                {...register("phoneNumber")}
              />
            </p>
            <p className="error-msg"> {errors.phoneNumber?.message} </p>
            <input type="submit"  id="submit" />
            </form>
    </div>
  );

CodePudding user response:

Because Yup receives an empty string instead of a number, it thinks you're passing the wrong type. You need to tell RHF to return undefined if the input is empty:

<input
  name="phoneNumber"
  type="text"
  {...register("phoneNumber", {
    setValueAs: (v) => {
      return v === "" ? undefined : parseInt(v, 10);
    }
  })}

Codesandbox Demo

  • Related