javascriptreactjsreduxecmascript-6redux-form

With redux form how can I normalize and allow only positive integers on an input type number?


I am on 8.3.7 version of redux-form, I am using the Field which should be allowed to accept ONLY positive integers between the range 0-9999.

const REGEX_SPECIAL_CHARACTERS = /[@\-\_\!\#\$\%\.\&]/;

<Field
    mandatory
    step={1}
    name="fieldName"
    type="number"
    min={0}
    max={9999}
    normalize={(value) => {
        console.log({value});
        return value?.split(REGEX_SPECIAL_CHARACTERS, 1).join('');
    }}
>
    Text
</Field>

I am using the normalize prop to validate this. If I enter 1.9, on blur it will set 1 which is ok. If I do -0 or -1 or just -n (n = any number) it just removes the entire value leaving an empty field and I need it to be ALWAYS 0 if there is whatever value going less than 0.

I do not know if maybe using the format prop but IDK how to use it => https://redux-form.com/8.3.0/docs/api/field.md/#-code-format-value-name-gt-formattedvalue-code-optional-

So any ideas on how I can fix this?


Solution

  • So this would immediately remove any characters that are not digits, thus only allowing positive integers:

    const onlyDigits = new RegExp('\\d+');
    const parsePositiveInt = (value) => {
        const matches = value.match(onlyDigits);
        return matches ? parseInt(matches[0]) : 0;
    };
    
    // ...
    
    normalize={(value) => parsePositiveInt(value).toString()}
    

    It's not converting 1.9 to 1 as you described, it would rather turn this into 19.