如何最初禁用提交按钮

如何最初禁用提交按钮

本文介绍了React Formik表单验证:如何最初禁用提交按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我在其中使用formikReact表单验证代码.默认情况下,加载表单时,我要保持禁用提交按钮:

Below is my React form validation code in which I am using formik. By default when the form loads, I want to keep the submit button disabled:

import { useFormik } from "formik";
import * as Yup from "yup";

const formik = useFormik({
    initialValues: {
      firstName: "",
      lastName: "",
      email: ""
    },
    validationSchema: Yup.object({
      firstName: Yup.string()
        .max(15, "Must be 15 characters or less")
        .min(3, "Must be at least 3 characters")
        .required("Required"),
      lastName: Yup.string()
        .min(3, "Must be at least 3 characters")
        .max(20, "Must be 20 characters or less")
        .required("Required"),
      email: Yup.string()
        .email("Invalid email address")
        .required("Required")
    }),
    onSubmit: values => {
      handleSubmit(values);
    }
  });

我尝试在按钮上使用它:

I have tried to use this on my button:

 disabled={!formik.isValid}

但是,只有在我尝试提交表单时,它才真正起作用.因此,如果我将表单保留为空白并单击提交",则会显示所有验证错误,然后禁用该按钮.但是,应该从一开始就将其禁用.我查看了文档,但那里没有任何明显的内容.

But it only actually works if I try to submit the form. So, if I leave the form blank and hit submit, all the validation errors show up and then the button is disabled. But, it should be disabled already from the start. I checked the documentation but didn't see anything obvious there.

推荐答案

如果要在加载表单时最初禁用submit按钮,则可以使用 Formikdirty : boolean 属性如下:

If you want to keep the submit button disabled initially when the form loads, you can use the use the dirty : boolean property of Formik something as below:

disabled={!formik.dirty}

如果要保持禁用submit按钮,直到所有字段值都有效,则可以使用 isValid: boolean ,其工作方式如下:

If you want to keep the submit button disabled until all the field values are valid then you can use isValid: boolean which works as below:

因此您可以将其用作:

disabled={!formik.isValid}

现在,如果要在所有字段均有效之前禁用提交按钮,并且如果字段值已从其初始值更改,则必须同时使用以上两个属性结合如下:

Now, if you want the submit button to be disabled until all the fields are valid and if the fields values have been changed from their initial values then you would have to use both of the above attributes in conjunction as below:

disabled={!(formik.isValid && formik.dirty)}

这篇关于React Formik表单验证:如何最初禁用提交按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 23:04