Give Formik Initial Error Values, Before Validation is Called

Viewed 1601

I have the following Form:

const MyForm = () => {
    return (
        <>
            <Formik
                validateOnChange={true}
                initialValues={{ plan: "", email: "", name: "" }}
                validate={values => {
                    console.log(values)
                    const errors = {}
                    if (values.plan !== "123" && values.plan !== "456") {
                        errors.plan = "Not valid"
                    } else if (values.plan === "") {
                        errors.plan = "Please enter something"
                    }
                    if (!values.email) {
                        errors.email = "Please provide an e-mail address."
                    } else if (
                        !/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i.test(values.email)
                    ) {
                        errors.email = "Please provide a valid e-mail address."
                    }
                    return errors
                }}
                onSubmit={(values, { setSubmitting }) => {
                    setTimeout(() => {
                        setSubmitting(false)
                    }, 400)
                }}
            >
                {({ isSubmitting, errors }) => (
                    <Form>
                        <FieldWrapper>
                            <InputField type="text" name="plan" label="plan" />
                            <StyledErrorMessage name="plan" component="div" />
                        </FieldWrapper>
                        <Button
                            disabled={errors.plan}
                        >
                            Continue
            </Button>
                    </Form>
                )}
            </Formik>
        </>
    )
}

I have a Continue Button and I want it to be disabled if there are any errors. I am doing <Button disabled={errors.plan}> and this works.

However: it does not disable to Button when the user just doesn't touch the field at all - since then, the validation isn't called and consequently, there won't be any errors in the error object. So initially, the button is not disabled.

How can I circumvent this?

1 Answers

I'm not too familiar with Formik, but could you add a state for completed status of the form, that is initially set to false, and when completed setState(true). Then your conditional for <Button> can check both errors.plan && completedState.

Related