验证redux -form textfield内部的道具



我正在努力处理一个任务几个小时。我有一个来自材料UI的redux表单文本字段,我这样使用它:

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

验证道具作为参数两个函数:

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)]}。错误未显示,但验证无法正常工作。有任何想法??

您的验证函数无法正常工作,因为validate prop期望具有值和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存储库的所有者和主要贡献者)建议定义您的参数化验证器的单个实例,而不是从validate Prop中传递参数,以防止对该领域的不必要重新渲染(例如,不执行Validate={[requiredValidator(intl), onlyNumeric(intl)]})。

最新更新