这个想法是让dynamicFields
从ownProps
它是第二个参数validate
的功能,并请你来填充验证使用它们。
由于combineValidators
是一个高阶函数,因此在运行它后,我们用values
as参数调用结果函数。
// 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