是否有方法将多个验证添加到React Final Form
中的单个字段?类似于:
<Field
name='email'
label='email'
validate={[emailValidator, emptyValidator}]
/>
redux-form
中也有类似类型的验证。有没有办法在React Final Form
中进行这种类型的验证?
您可以使用辅助函数(例如composeValidators
(为Field提供多个验证器
const required = value => (value ? undefined : 'Required');
const mustBeNumber = value => (isNaN(value) ? 'Must be a number' : undefined);
const minValue = min => value =>
isNaN(value) || value >= min ? undefined : `Should be greater than ${min}`;
const composeValidators = (...validators) => value =>
validators.reduce((error, validator) => error || validator(value), undefined);
并像一样使用它
<Field
name="age"
validate={composeValidators(required, mustBeNumber, minValue(18))}
/>
查看此处的官方示例现场级验证