使用 Redux Forms 在 FormSection 上使用验证
Using Validation on a FormSection with Redux Forms
有没有办法在 Redux Forms 中验证 FormSection?
我在 FormSection 中有两个复选框,我希望确保至少选中一个。
所需的功能已可用于其他 Field 组件,这不起作用是否有一些解决方法?
<FormSection name="fieldName" validate={required}>
<div className="form-body">
<Field
label="one"
name="one"
id="one"
component={CheckBox}
/>
<Field
label="two"
name="two"
id="two"
component={CheckBox}
/>
</div>
</FormSection>
作为解决方法,您可以使用表单级验证:https://redux-form.com/7.0.4/examples/syncvalidation/
在您的验证函数中,字段名称将以 FormSection 的名称为前缀。所以你的验证函数看起来像:
function validate(values){
const {fieldNameone, fieldNametwo} = values;
let errors = {};
if (fieldNameone === '' && fieldNametwo === '') {
errors.fieldNameone = 'Either field one or two must be filled in';
errors.fieldNametwo = errors.fieldNameone;
}
return errors;
}
我还没有测试过,所以它可能并不完美。
如果有帮助,您可以在 FormSection 容器中定义此函数以改进模块化。
我知道为时已晚,但它可能对某些人有用。您可以使用 getFormSyncErrors
选择器,然后检查是否有 属性 与您的部分名称然后您的部分无效
- 为部分创建单独的验证函数:
type FormSectionErrors = FormErrors<FormSectionValues, any>
const validateFieldName = (sectionValues: FormSectionValues) => {
const errors: FormSectionErrors
...
return errors
}
- 在您的主要验证中使用它:
const validate = (values: FormValues) => {
const errors: FormErrors<{ [fieldName]: FormSectionErrors } & FormValues, any>, any> = {}
errors[fieldName] = validateFormSectionValues(values[fieldName])
...
return errors
}
FormValues
应该在代码的其他地方定义。
any
很重要,因为 redux-form
的默认接口 FormError
否则会抛出错误。如果有人可以改进答案,请随意。
有没有办法在 Redux Forms 中验证 FormSection?
我在 FormSection 中有两个复选框,我希望确保至少选中一个。
所需的功能已可用于其他 Field 组件,这不起作用是否有一些解决方法?
<FormSection name="fieldName" validate={required}>
<div className="form-body">
<Field
label="one"
name="one"
id="one"
component={CheckBox}
/>
<Field
label="two"
name="two"
id="two"
component={CheckBox}
/>
</div>
</FormSection>
作为解决方法,您可以使用表单级验证:https://redux-form.com/7.0.4/examples/syncvalidation/
在您的验证函数中,字段名称将以 FormSection 的名称为前缀。所以你的验证函数看起来像:
function validate(values){
const {fieldNameone, fieldNametwo} = values;
let errors = {};
if (fieldNameone === '' && fieldNametwo === '') {
errors.fieldNameone = 'Either field one or two must be filled in';
errors.fieldNametwo = errors.fieldNameone;
}
return errors;
}
我还没有测试过,所以它可能并不完美。
如果有帮助,您可以在 FormSection 容器中定义此函数以改进模块化。
我知道为时已晚,但它可能对某些人有用。您可以使用 getFormSyncErrors
选择器,然后检查是否有 属性 与您的部分名称然后您的部分无效
- 为部分创建单独的验证函数:
type FormSectionErrors = FormErrors<FormSectionValues, any>
const validateFieldName = (sectionValues: FormSectionValues) => {
const errors: FormSectionErrors
...
return errors
}
- 在您的主要验证中使用它:
const validate = (values: FormValues) => {
const errors: FormErrors<{ [fieldName]: FormSectionErrors } & FormValues, any>, any> = {}
errors[fieldName] = validateFormSectionValues(values[fieldName])
...
return errors
}
FormValues
应该在代码的其他地方定义。
any
很重要,因为 redux-form
的默认接口 FormError
否则会抛出错误。如果有人可以改进答案,请随意。