Redux Form Validation firing on load (UPDATE_SYNC_ERRORS)

风流意气都作罢 提交于 2019-12-10 23:28:43

问题


All required fields have their validation triggered by UPDATE_SYNC_ERRORS on load of the form component. I don't think this is a bug I believe it to be a code issue (as it used to work - although I have recently updated)

So my question is - What could cause UPDATE_SYNC_ERRORS to fire at this stage? The field also has no value (undefined) yet passes through my function and fires an error as 'Required' like when a field has been touched.

export const required = value => value ? undefined : 'Required';

I can put an extra check in eg: value && value !== undefined ? undefined : 'Required'; but then I don't get the error when the textField has been touched.

Any ideas how to debug without totally stripping back? Cheers!


回答1:


In the last day I ran into this problem, too, and struggled to find any suitable solution, but through an amalgamation of lots of different issues on redux-form repo and lots of re-reading the docs and peeking at the source I've got something that should address your question. Granted, almost a year later, but hopefully it helps someone.

Note: The "magic" as it were is denoted by a comment so if your config object for reduxForm looks different I wouldn't pay much mind.

import { reduxForm, getFormValues, isDirty } from 'redux-form';

const formName = 'brilliantForm';

let MyForm = reduxForm({
    form: formName,
    enableReinitialize: true,
    asyncValidate,
    asyncBlurFields: [],
})(ComponentToWrap);

MyForm = connect(
    state => ({
        formValues: getFormValues(formName)(state),
        initialValues: {
            fieldOne: '',
            fieldTwo: '',
        },
        shouldValidate: () => isDirty(formName)(state), // This is the magic
    })
)(MyForm);

export default MyForm;

The gist here is that if there are initial values for your form redux-form is going to validate them by default unless you tell it not to via shouldValidate(). The isDirty selector makes quick work of limiting validation to after the form has been touched/interacted with.

NOTE: As of 7.1 shouldValidate() has been split up and deprecated in favor of shouldError() and shouldWarn().



来源:https://stackoverflow.com/questions/44366692/redux-form-validation-firing-on-load-update-sync-errors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!