我正在使用“ revalidate”来验证“ redux-form”表单,但是我面对这种情况,即存在一种基于API响应动态生成的表单,该表单将其映射并显示在表格。
以下是我通常如何使用“重新验证...”验证“ redux表单”的示例。
const validate = combineValidators({
name: composeValidators(
isRequired({ message: "Please enter your full name." }),
hasLengthLessThan(255)({
message: "Name can't exceed 255 characters."
})
)(),
email: composeValidators(
isRequired({ message: "Please enter your e-mail address." }),
matchesPattern(IS_EMAIL)({
message: "Please enter a valid e-mail address."
})
)()
});
export default compose(
connect(
null,
actions
),
reduxForm({ form: "signupForm", enableReinitialize: true, validate })
)(SignUpForm);
现在,我该如何使用自动生成的表单做类似的事情?
答案 0 :(得分:3)
想法是从dynamicFields
函数的第二个参数ownProps
中获取validate
,并在需要时使用它们填充验证。
由于combineValidators
是高阶函数,因此在运行它后,我们以values
作为参数调用结果函数。
// 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
,但您可以更具创造力,例如将type
传递到动态字段数据并执行类似if type === ABC then do XYZ
此处提供了完整的验证代码和框-> https://codesandbox.io/embed/py5wqpjn40?fontsize=14