I’m trying to validate a form before submitting using formik and yup validation. The form consist of two parts, the first form is validated then loads next one. And am setting a state handleShow(true) to trigger the second form. Below is my code
const UserOnboardSchema = Yup.object().shape({
gender: Yup.string().required('please select the gender'),
firstName: Yup.string().required('Please enter your first name'),
lastName: Yup.string().required('Please enter your last name'),
mobile: Yup.string()
.required('Please enter your mobile number')
.matches(phoneRegExp, 'Please enter valid phone number'),
workExperience: Yup.string().required('Please enter your work experience'),
});
const formik = useFormik({
initialValues: {
gender: '',
firstName: '',
lastName: '',
mobile: '',
workExperience: '',
currentRole: '',
},
validationSchema: UserOnboardSchema,
onSubmit: (values) => {
console.log(values);
formik.resetForm();
},
});
const handleSubmit = (e) => {
e.preventDefault();
formik.handleSubmit();
if (Object.entries(formik.errors).length === 0) {
handleShow(true);
} else {
handleShow(false);
}
};
Here is the problem in the handleSubmit the formik.handleSubmit is not working. It’s directly accessing the if/else condition thus loading second form without validating the first one.
if (Object.entries(formik.errors).length === 0) {
handleShow(true);
} else {
handleShow(false);
}
but if I givehandleShow(true) direclty to formik, like this
const formik = useFormik({
initialValues: {
gender: '',
firstName: '',
lastName: '',
mobile: '',
workExperience: '',
currentRole: '',
},
validationSchema: UserOnboardSchema,
onSubmit: (values) => {
console.log(values);
handleShow(true); #----> Giving here.
formik.resetForm();
},
});
then the formik and Yup validation works. Im unable to figure out whats causing this issue?