【问题标题】:Give Formik Initial Error Values, Before Validation is Called在调用验证之前给 Formik 初始错误值
【发布时间】:2020-11-09 13:59:05
【问题描述】:

我有以下表格:

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>
        </>
    )
}

我有一个Continue 按钮,如果有任何错误,我希望它被禁用。我正在做&lt;Button disabled={errors.plan}&gt;,这很有效。

但是:当用户根本不触摸该字段时,它不会禁用 Button - 从那时起,不会调用验证,因此不会出现任何错误在错误对象中。所以最初,按钮没有被禁用。

我该如何规避这个问题?

【问题讨论】:

    标签: javascript reactjs forms validation formik


    【解决方案1】:

    我对 Formik 不太熟悉,但您能否为表单的完成状态添加一个状态,最初设置为 false,完成后设置为 setState(true)。那么&lt;Button&gt; 的条件可以同时检查errors.plan &amp;&amp; completedState

    【讨论】:

      猜你喜欢
      • 2023-01-13
      • 2020-11-29
      • 2020-04-11
      • 2020-01-31
      • 2021-09-22
      • 2023-02-10
      • 1970-01-01
      • 2019-05-24
      • 2018-03-13
      相关资源
      最近更新 更多