jaredpalmer / formik

Build forms in React, without the tears 😭
https://formik.org
Apache License 2.0
33.88k stars 2.79k forks source link

isValid is false although all fields are valid #1116

Open burtek opened 5 years ago

burtek commented 5 years ago

🐛 Bug report

Current Behavior

According to validation reference FAQ returning undefined as error message is considered as marking field valid. Yet returning { fieldName: undefined } from validation function sets isValid tofalse thus preventing form from submitting. This is caused by following line in code:

https://github.com/jaredpalmer/formik/blob/85d15b302cd776eb615064a4451e1a7575b1439d/src/Formik.tsx#L425

Expected behavior

Returning { fieldName: undefined } from validation function should set isValid to true

Reproducible example

https://codesandbox.io/s/py95r24n7x

Typing anything in the field changes form state, but keeps isValid set to false

If you change validate to const validate = values => ({});, isValid will be set to true

Suggested solution(s)

At least change the docs. To make the validation work according to current docs, you'd need to check all values (incl. nested values) in object returned by validation function.

Your environment

Software Version(s)
Formik 1.3.2
motiazu commented 5 years ago

The documentation is pretty weird around that line. This is the code that decides whether you have errors. Object.keys(this.state.errors).length - this snippet pretty much means that any set field (even with undefined) will result in isValid being false.

I recommend clearing your own object of any undefined properties before returning the validation errors to formik. This could work before returning -

Object.keys(errors)
    .filter(key => errors[key] !== undefined)
    .reduce((res, key) => {
        res[key] = errors[key];
        return res;
    }, {})
webberwang commented 5 years ago

An issue relating to isValid, not sure if I should start a new issue.

I noticed that the isValid field stays false after submitting a form if the values are set using initialvalues. If the onChange is triggered, then the isValid will be correct.

https://codesandbox.io/s/302vp2wqxq

Example

barrett-vegas-com commented 5 years ago

@webberwang I ran into the same issue, but then found https://jaredpalmer.com/formik/docs/api/formik#isinitialvalid-boolean

jp94 commented 5 years ago

@webberwang This seems be to work for me. Using @barrett-vegas-com response with isInitialValid,

const validate = (values: Values): FormikErrors<Values> => { ... };
const isInitialValid = (values: FormikConfig<Values> & IProps) =>
  Object.keys(validate(values.initialValues)).length === 0;

withFormik({ ...  
 isInitialValid,
 validate
})
emil-alexandrescu commented 5 years ago

In case you are using yup

const isInitialValid = schema.isValidSync(initialValues);
jaredpalmer commented 5 years ago

This has been addressed is #1410

webpipl commented 5 years ago

An issue relating to isValid, not sure if I should start a new issue.

I noticed that the isValid field stays false after submitting a form if the values are set using initialvalues. If the onChange is triggered, then the isValid will be correct.

https://codesandbox.io/s/302vp2wqxq

Example

put this inside

isInitialValid={true}

its working .. on Edit Form initial values always true....

suggested Link

https://jaredpalmer.com/formik/docs/api/formik#isinitialvalid-boolean

vinodh99 commented 5 years ago

Is there a way to set the is valid manually? When I set the field value from session storage and pass the same value to the initial values, the invalid is being set to true upon error though I trigger setFieldError.

rob10e commented 5 years ago

@vinodh99 Try this:

const initialValues = {
... initial values
};
<Formik
  .... other props
  initialValues={initialValues}
  validationSchema={schema}
  isInitialValid={schema.isValidSync(initialValues)}
>
... rest of code
</ Formik>
andrew-aladev commented 3 years ago

This issue has been fixed in 2.x only, 1.x versions has to use isInitialValid.

pdancewicz commented 3 years ago

I'm still having this issue. I'm using version 2.1.5 and even without any validation isValid is always false

jrrewers commented 3 years ago

I'm still having this issue. I'm using version 2.1.5 and even without any validation isValid is always false

Have you managed to find a way around or a fix for this?

andrew-aladev commented 3 years ago

Hello guys, I am using formik@1.4.3 and the following code works perfect:

<Formik
  initialValues={initialValues}
  validationSchema={schema}
  isInitialValid={() => schema.isValidSync(initialValues)}
  onSubmit={onSubmit}
  enableReinitialize
>
...

Please try with your projects.

jrrewers commented 3 years ago
  isInitialValid={() => schema.isValidSync(initialValues)}

That works, thanks! But when I do isInitialValid={schema.isValidSync(initialValues)} it fails.

quorak commented 3 years ago

I also needed the initial error object to be correct. I wrote this little helper for sync cases:

import { useMemo } from 'react'
import { FormikErrors, yupToFormErrors } from 'formik'
import { ObjectSchema } from 'yup'

export default function useInitialErrorsSync(
  schema: ObjectSchema,
  initialValues: any,
): [boolean, FormikErrors<any>] {
  const values: [boolean, FormikErrors<any>] = useMemo(() => {
    try {
      schema.validateSync(initialValues, { abortEarly: false })
    } catch (err) {
      if (err.name === 'ValidationError') return [false, yupToFormErrors(err)]
    }
    return [true, {}]
  }, [])
  return values
}

can be used like

  ...
  const [isInitialValid, initialErrors] = useInitialErrorsSync(schema, initialValues)
  return <Formik
                  validateOnChange
                  validateOnBlur
                  validateOnMount
                  validationSchema={schema}
                  isInitialValid={isInitialValid}
                  initialErrors={initialErrors}
                  initialValues={initialValues}
                  onSubmit={onSubmit}
                >
   ...
EDMONDGIHOZO commented 3 years ago

isInitialValid is deprecated and will be removed in formik soon, it is advised to use validateOnMount

maciej-wira commented 2 years ago

Hello guys, I am using formik@1.4.3 and the following code works perfect:

<Formik
  initialValues={initialValues}
  validationSchema={schema}
  isInitialValid={() => schema.isValidSync(initialValues)}
  onSubmit={onSubmit}
  enableReinitialize
>
...

Please try with your projects.

In my case enableReinitialize was the game changer.