Search code examples
javascriptreactjsreact-nativeredux-formredux-form-validators

multiple normalizer in redux form


I want to pass multiple functions for normalizing redux fields, is there a way to do so? like we pass a array in validation prop?

validate={[alphanumeric,maxlength]}

throughout redux-form questions i saw ways like

normalize={maxlength_alphanumeric(5)} //but here two logic are burried in one function

how to implement something like

normalize={maxlength(5) , alphanumeric}

Solution

  • We can implement this using closures, so we create a function that accept an array of normalization functions.

    Note that this is different from validation because in validation all functions are not related if one of them fail it means validation failed.

    While in normalization the value passed to each normalization function needs to be passed from the previous function that already did some normalization.

    So we can do that using the normalizeAll function below

    function normalizeAll(normalizers){
        return function(value , previousValue , allValues , previousAllValues){ //note that these arguments are passed by default from redux form
            var i = 0;
            var normalizersLength = normalizers.length;
            var currentValue = value;
            while(i < normalizersLength)
            {
                var currentNormalizer = normalizers[i];
                if(typeof currentNormalizer == "function")
                {
                    currentValue = currentNormalizer(currentValue ,previousValue , allValues , previousAllValues);
                }
                i++;
            }
    
            return currentValue;
        }
    }
    
    //I am using only the `value` argument in normalization functions just for the example, but you can use the rest of them if they are needed
    var firstNormalization = function(value , previousValue , allValues , previousAllValues){
        return value+1;
    }
    
    var secondNormalization = function(value, previousValue , allValues , previousAllValues){
        return value+2;
    }
    
    var thirdNormalization = function(value, previousValue , allValues , previousAllValues){
        return value+3;
    }
    
    //To test result: i will execute the function returned from normalizeAll and pass the first argument as 1.
    var normalizedValue = normalizeAll([firstNormalization , secondNormalization , thirdNormalization])(1); 
    console.log(normalizedValue); // 7 
    


    To use normalizeAll now in your redux form you will do something like this

    normalize={normalizeAll([firstNormalizationFunction , secondNormalizationFunction])}
    


    Note that this is assuming that all normalization functions are synchronous, i don't think that we usually have use cases where normalization function needs to be async, but the solution will still be the same but then we will use callback functions or promise