在redux -form的textfield中验证prop

时间:2017-09-22 12:53:44

标签: reactjs redux-form react-intl

我正在努力应对任务几个小时。 我有一个来自材料ui的redux表单文本字段,我使用它:

<Field
          id="searchCif"
          name="searchCif"
          component={TextField}
          floatingLabelText={SEARCHVIEW_HINT_CIF}
          disabled={(afm !== undefined)}
          validate={[requireValidator, onlyNumeric]}
        />

validate prop将两个函数作为参数:

const requireValidator = (value, intl) => (
  value === undefined ? intl.formatMessage({ id: 'error.search.cif.afm' }) :
    undefined
);

const onlyNumeric = (value, intl) => (
  (value !== undefined && !(/^([0-9])+$/g).test(value)) ?
    intl.formatMessage({ id: 'error.search.cif.afm.only.number' }) :
    undefined
);

我使用intl因为我的消息应该被翻译。但是错误显示intl.formatted message is not a function。因此我写道: validate={() => [requireValidator(value, intl), onlyNumeric(value, int)]}。错误未显示但验证无法正常工作。任何想法??

1 个答案:

答案 0 :(得分:1)

您的验证功能无法正常工作,因为Validate prop expects是一个带有value和allValues参数的函数。将函数包装在另一个函数中以传递其他参数。

const requireValidator = intl => value => (
    (value === undefined) ? 
    intl.formatMessage({ id: 'error.search.cif.afm' }) : undefined
);

const requireValidatorInternationalized = requireValidator(intl);

const onlyNumeric = intl => value => (
  (value !== undefined && !(/^([0-9])+$/g).test(value)) ?
    intl.formatMessage({ id: 'error.search.cif.afm.only.number' }) :
    undefined
);

const onlyNumericInternationalized = onlyNumeric(intl);

<Field
      id="searchCif"
      name="searchCif"
      component={TextField}
      floatingLabelText={SEARCHVIEW_HINT_CIF}
      disabled={(afm !== undefined)}
      validate={[requireValidatorInternationalized, onlyNumericInternationalized]}
    />

Erikras(redux-form存储库的所有者和主要贡献者)advises定义参数化验证器的单个实例,而不是从Validate prop传递参数以防止不必要的重新呈现字段(例如不要做Validate={[requiredValidator(intl), onlyNumeric(intl)]})。