当用户单击“提交”按钮时,Yup无法验证复选框

时间:2020-02-09 11:53:16

标签: javascript reactjs formik yup

我在React应用程序中具有以下Yup配置:

 const schema = yup.object().shape({
        email: yup.string()
            .email('E-mail is not valid!')
            .required('E-mail is required!'),
        password: yup.string()
            .min(6, 'Password has to be longer than 6 characters!')
            .required('Password is required!'),
        tandc: yup.boolean()
            .oneOf([true], "You must accept the terms and conditions")
    })

我的表单如下(使用Formik):

 <Form>
                    <div className="form-group">
                        <label >Email
                        <Field type="email" name="email" className="form-control" />
                        </label>
                        <ErrorMessage name="email" component="div" className="invalid-feedback" />
                    </div>
                    <div className="form-group">
                        <label >Password
                        <Field type="password" name="password" className="form-control"  />
                        </label>
                        <ErrorMessage name="password" component="div" className="invalid-feedback" />
                    </div>
                    <div className="form-group">

                        <Field type="checkbox" name="tandc" className="form-check-input"  id="tandc" />
                        <ErrorMessage name="tandc" component="div" className="invalid-feedback" />
                        <label htmlFor="tandc" >I agree to the Terms and Conditions
                        </label>
                    </div>

                    <PrimaryButton label="Login" disabled={isSubmitting} type="submit">
                        Submit
                    </PrimaryButton>
                </Form>

如果用户单击表单上的提交,则Yup会验证电子邮件和密码字段,但会忽略复选框字段:

enter image description here

仅当我先选中然后取消选中条款和条件时,我才能使复选框验证生效。

我如何使它工作,以便在用户仅单击提交按钮时显示错误消息?

2 个答案:

答案 0 :(得分:1)

根据Yup存储库中的issue

如果将其与formik一起使用,请确保设置initialValues = {termsOfService: false}

答案 1 :(得分:0)

对于

<button className="previous-round" onClick={() => setOrderData_(previous(orderData_))}>
&#8249;
</button>

要工作,您必须将该字段的初始值设置为yup.boolean().oneOf([true],'Message'); true

在您的情况下,看起来像这样

false

无论您在哪里设置初始值