Search code examples
reduxnormalizationredux-form

Normalize is called only once in redux form


i'm using a normalizer for pad from left a user's input. My function is this:

export const padLeft = (num, len) => (
  len > num.toString().length ? '0'.repeat(len - num.toString().length) + num
    : num
);

and my normalizer is this:

const normalizeCid = (value) => {
  return padLeft(value, 8);
};

When i use it in my Field component like this:

<Field
        id="searchCif"
        name="searchCif"
        floatingLabelText={SEARCHVIEW_HINT_CIF}
        component={InputTextField}
        disabled={(props.afm !== undefined)}
        normalize={normalizeCid}
      />

and i type an input for example 2 it shows me 00000002 which is correct but when i type 23 the zeros are not reducing. It shows me 000000023. Why is this happening?


Solution

  • I think the function normalizeCid is running with each value change, but first time you run it and type '2', the value that get passed to padLeft is 2, and it returns and displays 00000002.

    Then, when you add a '3' to to the displayed value (00000002), the value that gets passed into padLeft is 000000023, which has length of 9, which is greater than 8, so it just returns the original value.

    So the issue is faulty logic in the padLeft function.

    The padLeft function seems to work as long as it gets passed a number without any leading zeros, so we could possibly fix the issue by using Regex to remove the leading zeros before we pass the value to padLeft:

    const normalizeCid = (value) => {
      const noLeadingZeros = value.toString().replace(/\b(0+)/, '');
      return padLeft(noLeadingZeros, 8);
    };
    const padLeft = (num, len) => (
      // num is already a string now
      len > num.length ? '0'.repeat(len - num.toString().length) + num
        : num
    );
    

    NOTE: This suggestion probably doesn't work with all edge cases, so you may have to add some extra condition somewhere.