React formik form validation: How to initially have submit button disabled

前端 未结 3 1519
孤城傲影
孤城傲影 2021-02-05 08:20

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:



        
3条回答
  •  长发绾君心
    2021-02-05 09:04

    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}
    

    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:

    Returns true if there are no errors (i.e. the errors object is empty) and false otherwise.

    So you may use it as:

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

提交回复
热议问题