在redux-form中显示错误消息onChange

时间:2017-03-28 17:57:13

标签: reactjs material-ui redux-form

我尝试使用redux-form Field(与Material-ui一起)和验证。当我离开字段(即onBlur)时,似乎显示错误消息。我想要实现的是在用户输入时动态进行验证,并在onChange事件上显示错误消息。我将如何实现这一行为?

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

2 个答案:

答案 0 :(得分:3)

验证的默认行为是仅在触摸字段时显示消息(即onBlur)。

我想你可以通过使用componentWillMount中的touch方法解决这个问题,以便在mount时触及它:

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

然而,这确实存在可能在加载表单时直接显示任何错误的缺点,但在这种情况下,立即在onChange中触发验证。

答案 1 :(得分:2)

你在CodeSandbox中玩过这个例子吗?像丹尼斯建议的那样,你可以打电话给#34;触摸&#34;,虽然根据你的需要,你可以选择改变:

  <Field
    name="username"
    type="text"
    component={renderField}
    label="Username"
    onChange={() => touch('username')}
  />