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

て烟熏妆下的殇ゞ 提交于 2019-11-30 20:37:58

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!