Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying error messages onChange in redux-form

I'm trying to use redux-form Field (together with Material-ui) and validation. It appears that the error messages are shown when I navigate away from the field (i.e. onBlur). What I would like to achieve is to do validation on the fly as the user types, and display error messages onChange event. How would I go about achieving this behavior?

import { TextField } from 'redux-form-material-ui';
import { Field, reduxForm } from 'redux-form';

const MyForm = (props) => (
  <form>
      <div className="form-group">
        <Field
          name="foo"
          type="text"
          hintText="Foo"
          component={TextField}
        />
  </form>
);

export default reduxForm({
  form: 'MyForm',  
  validate             
})(MyForm);
like image 879
foobar Avatar asked Mar 28 '17 17:03

foobar


2 Answers

The default behaviour of validation is that messages are only displayed when fields are touched (i.e. onBlur).

I suppose you could work around that by using the touch method in componentWillMount, so that it becomes touched upon mount:

componentWillMount() {
  const { touch } = this.props;
  touch('foo');
}

That does however have the drawback of possibly showing any errors directly when the form is loaded, but in this case validation is triggered in onChange right away.

like image 103
Dennis Avatar answered Oct 23 '22 18:10

Dennis


Have you played with the example in CodeSandbox? Like Dennis suggested, you could call "touch", though depending on your need you may choose to do this onChange:

  <Field
    name="username"
    type="text"
    component={renderField}
    label="Username"
    onChange={() => touch('username')}
  />
like image 28
ovation22 Avatar answered Oct 23 '22 16:10

ovation22