How to have submit and field validation at the same time in formik?

50 Views Asked by At

i want to validate form on submit with formik, while also have field level validation.For example, validate all fields when submitting, and validate a field on change.

 return (
    <div className='add-member'>
      <h1>Register a new member</h1>
      <Formik
        validationSchema={validationSchema}
        validateOnBlur={false}
        validateOnChange={false}
        initialValues={{ name: ''}}
        onSubmit={() => {
          console.log('something')
        }}
      >
        {({errors}) => (
          <Form>
            <div className='member-info'>
              <div className='title'><p>Info</p></div>
        
              <div className='input' id='name-input'>
                <label>Name</label>
                <Field name='name' placeholder={errors.name ? '*Required' : null} className={errors.name ?      'input-error' : ''} />
              </div>
      </Formik>
    </div>
  )
 

I have disabled validateOnChange in the Formik component so that submit validation works, but dont know how to validate a field on change.

1

There are 1 best solutions below

3
Tyne On

Well, you can try to do form validation using Yup with validationSchema. And also you should use useFormik hook instead of Formik component.

Then you may reach the correct response.

For example

const formik = useFormik({
    initialValues,
    validationSchema: registrationSchema,
... the code that you want
const registrationSchema = Yup.object().shape({
fieldName: Yup.string()
.oneOf([Yup.ref('')], "example commit"),

Maybe, you will get success.