Search code examples
reactjsformikreact-componentyup

React Formik ErrorMessage error always shwoing


render={({ errors, touched }) => (
        <Form onSubmit={submitBook}>
         <FormGroup>
          <label htmlFor="Name">Full Name</label>
            <Field
              value={book.bookingCustomerName}
              onBlur={() => book.setFieldTouched('Name')}
              onChange={e => setBook({...book,bookingCustomerName: e.target.value})}
              className="form-control"
              name="Name"
              placeholder="Jay Sankar Bhat"
              type="text"
            />
            <ErrorMessage
              name="Name"
              component="div"
              className="field-error text-danger"
            />
         </FormGroup>

This the Formik Component . Even after putting the value in the Field the Error Message is being rendered. Why is this happening? Form Image

Below is the whole code:

    let packageType = useParams();
    packageType = packageType.package;
    let history = useHistory();
    let [message,setMessage] = useState({
      msg: '',
      color: 'danger'
    });
    let [pack,setPack] = useState(0);
    let [price,setPrice] = useState(0);
    let [isApplied,setIsApplied] = useState(false);
    let [isSubmitted,setIsSubmitted] = useState(false);
    let [book,setBook] = useState({
        bookingPackageType: packageType,
        bookingCustomerName: '',
        customerMobile: '',
        bookingDate: '',
        bookingSlot:'',
        address: '',
        comment: '',
        promoCode: ''
    });

Booking Schema using Yup. This is used as ValidationSchema:

const BookingSchema = Yup.object().shape({
    bDate: Yup.string()
      .required("Inspection Date required"),
    Name: Yup.string()
      .min(2, "Must be longer than 2 characters")
      .max(50, "Nice try, nobody has a first name that long")
      .required("Name Required"),
    mobile: Yup.string()
      .min(10, "Enter 10 Digits Mobile Number")
      .max(10, "Enter 10 Digits Mobile Number")
      .required("Mobile Number Required")
  })

Solution

  • This is what you need to do:

    {book.bookingCustomerName===""?
    <ErrorMessage
                  name="Name"
                  component="div"
                  className="field-error text-danger"
                />
    :null}
    
    

    simply add a check condition that if your value is empty then show the error message otherwise don't.