Source:  Twitter logo

I am creating a form by using react and formik.Below is my code:

<div>
  <Formik
    initialValues={{
      email: ""
    }}
    onSubmit={(values: FState, setSubmitting: any) => {
      console.log("Enter in submit function", values);
      setTimeout(() => {
        alert(JSON.stringify(values, null, 2));
        setSubmitting(false);
      }, 500);
    }}
    validationSchema={validationSchemaGlobal}
  >
    {({
      errors,
      touched,
      handleBlur,
      handleChange,
      isSubmitting,
      values,
      handleSubmit
    }: any) => (
      <div>
        <Cards>
          <form onSubmit={handleSubmit}>
            <CardBody>
              <h4>
                Enter Your Email Address and we'll send you a link to reset your
                password
              </h4>
              <Field
                type="text"
                id="email"
                value={values.email}
                component={CustomInput}
                onChange={handleChange}
                onBlur={handleBlur}
              />
              {errors.email && touched.email ? (
                <div style={{ color: "red" }}>{errors.email}</div>
              ) : null}
            </CardBody>
            <CardFooter>
              <br />
              <button type="submit" disabled={isSubmitting}>
                Send Password Reset Link
                {/* {isSubmitting && <i className="fa fa-sponner fa-spin"/>} */}
              </button>
            </CardFooter>
          </form>
        </Cards>
      </div>
    )}
  </Formik>
</div>

In this formik form, onSubmit function not working. I dont know why? Please tell me guys what is problem with my code?

Check your validationSchema. I ran into this problem and found that my validator was returning something that signaled to Formik the form was invalid, but no other warnings or messages were coming up. It just wouldn't submit.

Replace that prop with validator={() => ({})} i.e. just an empty object being returned. That should pass validation and trigger your onSubmit. You can restore your functionality from there.

  <Formik
    initialValues={{
      email: ""
    }}
    onSubmit={() => { console.log("submit!"); }}
    validator={() => ({})}
  >
    {/* */}
  </Formik>
178 users liked answer #0dislike answer #0178
Chris profile pic
Chris

In my case I use Yup as validator and I accidentally had firstName and lastName in my validationSchema as required but I did not have those values in my form.

My validationSchema was,

const SignupSchema = Yup.object().shape({
  firstName: Yup.string()
    .min(2, 'Too Short!')
    .max(50, 'Too Long!')
    .required('Required'),
  lastName: Yup.string()
    .min(2, 'Too Short!')
    .max(50, 'Too Long!')
    .required('Required'),
  email: Yup.string()
    .email('Invalid email')
    .required('Required'),
  password: Yup.string()
    .min(6, 'Password must be at least 6 characters')
    .max(24, 'Password can be maximum 24 characters')
    .required('Required')
}) 

I just deleted firstName and lastName,

const SignupSchema = Yup.object().shape({
  email: Yup.string()
    .email('Invalid email')
    .required('Required'),
  password: Yup.string()
    .min(6, 'Password must be at least 6 characters')
    .max(24, 'Password can be maximum 24 characters')
    .required('Required')
})

So check your validationSchema and see if you require something that does not exist in your form.

33 users liked answer #1dislike answer #133
Hasan Sefa Ozalp profile pic
Hasan Sefa Ozalp

I imported Form from react-bootstrap instead of formik, so I was having this issue. The issue was solved by importing the Form of formik. Sometimes, directly using Form.Control of react-bootstrap instead of Field of formik also gives this issue.

If you really have to use Form.Control you can use render prop.

10 users liked answer #2dislike answer #210
Bhuwan Adhikari profile pic
Bhuwan Adhikari

In my case, onSubmit was not working because I forgot to wrap my form in the <form></form> tag. A stupid issue, but it can be the reason for this behavior. If the above solutions don't work, check that you have the form tag.

4 users liked answer #3dislike answer #34
Anna Logacheva profile pic
Anna Logacheva

A little bit late for the original question but I experienced the same issue and solved it easy but hard to find.

When I passed the "name" prop to the component I had written "DateOfBirth" instead of with lowercase, which means it didn't match my validationSchema.

My schema looks like this:

export const userSchema = yup.object().shape({
firstName: yup.string().min(1).max(50).required('Field is required'), 
lastName: yup.string().min(1).max(50).required('Field is required'), 
dateOfBirth: yup.date().required('Invalid input'),});

This menas the name of the component has to match

Before (Didn't work):

 <DateTimePicker name="DateOfBirth" label="Date of birth" />

After (Worked):

<DateTimePicker name="dateOfBirth" label="Date of birth" />
3 users liked answer #4dislike answer #43
Huezzer profile pic
Huezzer

I am mentioning one more possibility through which i handled. change the button type and add onClick like this

<Button type="button" onClick={submitForm}>

also add submitForm prop at top along with values, touched etc

 {({ submitForm, errors, handleChange, handleSubmit, touched, values }) => (

now its working

1 users liked answer #5dislike answer #51
saud00 profile pic
saud00

My mistake was I was not initializing error with blank on validation

 const errors:any={};

Here is full code for login form, check the validate function

    <Formik
     initialValues={{ email: "", password: "" }}
     validate={(formValues) => {
         const errors:any={};
         if (!formValues.email) {
             errors.email = "Invalid email";
         }
         if (!formValues.password) {
             errors.password = "Password is required";
         }
         return errors;

     }}
     onSubmit={async (values) => {
         console.log("submit", values);
         dispatch(login({ username: values.email, password: values.password }));
         if (loginState.isError) {
             alert(loginState.message);
         }
     }}
 >{({ values, handleChange, errors, dirty, isValid, isSubmitting, handleSubmit, setFieldValue, setFieldTouched, setFieldError }) => (
     <Form onSubmit={handleSubmit}>
         <FormGroup>
             <Label>Email</Label>
             <Input type="email" name="email" valid={!isEmpty(errors.email)} value={values.email} onChange={handleChange}></Input>
             <FormFeedback className="font-weight-bold" type="invalid" role="alert"> {errors.email}</FormFeedback>
         </FormGroup>
         <FormGroup>
             <Label>Password</Label>
             <Input type="password" name="password" value={values.password} valid={!isEmpty(errors.password)} onChange={handleChange}></Input>
             <FormFeedback className="font-weight-bold" type="invalid" role="alert"> {errors.password}</FormFeedback>

         </FormGroup>
         <FormGroup className="text-center">
         <p> {isValid === true ? "is valid" : "not valid"} </p>
             <Button type="submit" color="primary" className="mt-3">Login</Button>
         </FormGroup>
     </Form>
 )}
 </Formik>
0 users liked answer #6dislike answer #60
Nishant Kumar Verma profile pic
Nishant Kumar Verma

This may be because the form is being submitted and it's is invalid , this may happen because validation schema is not matching ur form for more than one reason ,

in my case , it was because there was a string , and it is been sent as null , so I just added .nullable() to the validation schema for that field.

0 users liked answer #7dislike answer #70
rawand deheliah profile pic
rawand deheliah

I solved this because I declared the onsubmit function without the const word (I know it's stupid)

0 users liked answer #8dislike answer #80
Farouk Elayache profile pic
Farouk Elayache

Use instead of button tag as i worked for me.

-3 users liked answer #9dislike answer #9-3
Raja Boddu profile pic
Raja Boddu

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).