Home > Enterprise >  Redirect to next page after validating with yup
Redirect to next page after validating with yup

Time:03-02

I have a form that take only one user input. Also i used react formik for the form and yup for validation.

I want the user to be taken to next page after the input is validated.

Validation is working but on click of the next page button does not take to next page.

Here is my code;

.
.
.

const Home = () => {

const navigate = useNavigate()

const initialValues = {
  phoneNumber: ''
}

const onSubmit = values => {
  console.log('form data', values)
  navigate.push("/NextPage")
}

const validationSchema = Yup.object({
phoneNumber: Yup.string()
    .min(11, 'Invalid phone number format!')
    .max(11, 'Invalid phone number format!')
    .required('Please enter your phone number!'),
})


return (
    {/*...*/}

  <Formik 
    initialValues={initialValues}
    validationSchema={validationSchema}
    onSubmit={onSubmit}>

    <Form className='phone-input'>
      <Field 
          type='tel' 
          id='phone-input' 
          name='phoneNumber' 
          placeholder='0000-000-0000'
        />
        <ErrorMessage name='phoneNumber'>
          {
            (errorMsg) => <div className='error'>{errorMsg}</div>
          }
        </ErrorMessage>
        <button type='submit' id="phoneBtn"  onClick={onSubmit}>Next Page</button>
          
    </Form>
      
    </Formik>
  
    </div> 
    )
    }

    export default Home

CodePudding user response:

I don't think you need to do .push() to navigate. Just use-

navigate("/NextPage")
  • Related