您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

使用redux-form验证React中动态生成的表单并重新验证?

使用redux-form验证React中动态生成的表单并重新验证?

这个想法是让dynamicFieldsownProps它是第二个参数validate功能,并请你来填充验证使用它们。

由于combineValidators一个高阶函数,因此在运行它后,我们用valuesas参数调用结果函数

// 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)

}

在此示例中,我只是放置,isrequired但您可以更具创造力,例如将a传递type到动态字段数据并执行类似if type === ABC then do XYZ

此处提供了完整的验证代码和框->https://codesandbox.io/embed/py5wqpjn40?fontsize=14

其他 2022/1/1 18:15:42 有430人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶