Search code examples
redux-form

Redux-form validation breaks when using multiple components with the same form name


I run into the validation issue using multiple components decorated with same form name.

Let's say we have SimpleForm1 and SimpleForm2. When rendering Only SimpleForm1 with the name field validation works as expected, as well as when rendering SimpleForm2 with the surname field. But when rendering them both on a single page validation for SimpleForm1 is broken.

The question is how to avoid such behaviour and make both validation functions work.

Here is a fiddle which illustrates my problem


Solution

  • It's not a good idea to use same names for multiple forms. As i understand you need to dynamically add form inputs(SimpleForm2 in your example) and have possibility to submit both forms with one button. If yes, so you can add just an input to first form, you don't need second form.

    Form:

    const SimpleFormComponent1 = props => {
        const {handleSubmit, pristine, reset, submitting, renderBoth} = props;
        const onSubmit = (values) => {
            alert(JSON.stringify(values));
        };
    
        return (
            <form onSubmit={handleSubmit(onSubmit)}>
                ...
                {
                    renderBoth &&
                    <Field
                        name="surname"
                        type="text"
                        component={renderField}
                        label="Surname"
                        validate={validateSurname}
                    />
                }
                ...
            </form>
        )
    };
    

    Render function:

    render() {
            const {renderBoth} = this.state;
    
            return (
                <div>
                    <div className='forms'>
                        <SimpleForm renderBoth={renderBoth}/>
                    </div>
                    <button
                        type='button'
                        onClick={this.handleClick}>
                        {renderBoth ? 'Show Single' : 'Show Both'}
                    </button>
                </div>
            );
        }
    

    Updated example