RamAlx
RamAlx

Reputation: 7344

Validate prop inside textfield of redux -form

I'm struggling cope with a task for a couple of hours. I have a redux form text field from material ui and i use it like this:

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

The validate prop take as arguments two functions:

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

I use intl because my message should be translated. But an error is showing that intl.formatted message is not a function. Therefore i wrote: validate={() => [requireValidator(value, intl), onlyNumeric(value, int)]}. The error is not showing but the validation is not working properly. Any ideas??

Upvotes: 1

Views: 217

Answers (1)

cagefree
cagefree

Reputation: 37

Your validation function is not working correctly because the Validate prop expects a function with the value and allValues params. Wrap the function in another function to pass in your additional parameters.

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 (owner and main contributor to the redux-form repository) advises defining a single instance of your parameterized validator instead of passing in the parameter from the Validate prop to prevent unnecessary re-rendering of the field (e.g. don't do Validate={[requiredValidator(intl), onlyNumeric(intl)]}).

Upvotes: 1

Related Questions