Validate dynamically generated form in react using redux-form and revalidate?

后端 未结 1 1035
花落未央
花落未央 2021-01-05 07:47

I\'m using \"revalidate\" to validate \"redux-form\" forms, but I\'m facing this situation where there\'s a form that is generated dynamically based on an API response that

1条回答
  •  生来不讨喜
    2021-01-05 08:12

    The idea is to get the dynamicFields from the ownProps which is the second argument of the validate function and use them as you please to populate the validation.

    Since combineValidators is an high order function, after running it we call the resulting function with values as parameter.

    // assuming dynamicFields an array like:
    [
        {
            id: 1,
            name: 'age',
            component: 'input',
            label: 'Age',
            placeholder: 'Age'
        },
        {
            id: 2,
            name: 'size',
            component: 'input',
            label: 'Size',
            placeholder: 'Size'
        }
    ]
    ///////
    
    const validate = (values, ownProps) => {
    const staticValidations = {
        firstname: composeValidators(
            isRequired({ message: 'Please enter the first name.' }),
            hasLengthLessThan(255)({
                message: "Name can't exceed 255 characters."
            })
        )(),
        lastname: composeValidators(
            isRequired({ message: 'Please enter the lastname' }),
            matchesPattern('abc')({
                message: 'Please enter a valid lastname'
            })
        )()
    }
    const dynamicValidations = ownProps.dynamicFields.reduce((accu, curr) => {
        accu[curr.name] = isRequired({ message: 'Please enter ' + curr.name })
        return accu
    }, {})
    
    return combineValidators({
        ...staticValidations,
        ...dynamicValidations
    })(values)
    

    }

    In this example I am just putting the isRequired but you can be more creative, e.g. passing a type to your dynamic field data and doing things like if type === ABC then do XYZ

    A full codesandbox of the validation is provided here -> https://codesandbox.io/embed/py5wqpjn40?fontsize=14

    0 讨论(0)
提交回复
热议问题