Formik onSubmit function is not working on my code

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?

67896 次浏览

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>

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.

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.

Use instead of button tag as i worked for me.

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" />

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.

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>

This may happen because the form is being submitted but it is invalid , this may happen because the 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.

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

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

In my case, mistakenly I have passed validationSchema to wrong prop.

Error:

  <Formik
initialValues={initialValues}
validate={validationSchema} <----- Error
>

Proper way:

  <Formik
initialValues={initialValues}
validationSchema={validationSchema} <----- Good
>

Had extra field in my validationSchema which was declared with Yup. however that field wasn't declared in Formik hence it didn't work. After removing the field from validationSchema, it works.