Pachu Pachu - 2 months ago 36
React JSX Question

Redux-Form - validation happens only once

I'm new to redux-form, and I followed this simple example: http://redux-form.com/6.0.5/examples/syncValidation/

I did everything it says but for some reason the validation function I'm passing is invoked only once, at the creation of the form, and it doesn't invoke when values are changed.

Here is my code:

reducer:

import { combineReducers } from 'redux-immutable';
import { reducer as formReducer } from 'redux-form/immutable';

export const appReducers = combineReducers({
form: formReducer
});


my form:

import React, { PropTypes } from 'react';
import { Field, reduxForm } from 'redux-form';
import TextField from 'react-mdl';

class Form extends React.Component {
constructor(props) {
super(props);

this.state = {
user: Map({
id: '',
name: ''
})
};

this.onIdChange = this.onIdChange.bind(this);
this.onNameChange = this.onNameChange.bind(this);
}

onIdChange(event) {
// change the id in the user.
}

onNameChange(event) {
// change the name in the user.
}

render() {
const { handleSubmit } = this.props;

return (<form onSubmit={handleSubmit}>
<Field name='id'
label='id'
component={TextField}
onChange={this.onIdChange}
value={this.state.user.get('id')} />
<Field name='name'
label='name'
component={TextField}
onChange={this.onNameChange}
value={this.state.user.get('name')}/>
</form>);
}
}

const validate = values => {
const errors = {};

if (!values.id) {
errors.id = 'Required';
}

if (!values.name) {
errors.name = 'Required';
}

return errors;
}

export default reduxForm({
form: 'userForm',
validate
})(Form);

Answer

If you are using an immutable import

import { reducer as formReducer } from 'redux-form/immutable';

for the reducer. You should also use the same for the actual form imports like this:

import { Field, reduxForm } from 'redux-form/immutable';

If this doesn't fix the problem I think there's something wrong with onChange and the custom handlers you defined(onNameChange) that are changing inner state.