如何配置Mobx React Form仅在字段UI存在时触发校验
解决方案
针对mobx-react-form条件渲染字段仍触发校验的问题,有两种常用的实现方案,你可以根据业务需求选择:
方式1:动态配置条件校验规则
mobx-react-form 原生支持将字段的rules属性设置为函数,函数可获取当前表单实例,从而读取其他字段值动态返回校验规则。你只需要让height的required规则和UI渲染的判断条件保持完全一致即可:
fields: [ { name: "workflowTypeId", bindings: "TextField", }, { name: "height", label: "Height", bindings: "TextField", rules: (form) => { // 此处判断条件和你UI层渲染height字段的条件保持完全一致即可 const needRenderHeight = form.$('workflowTypeId').value === '你需要展示height的对应workflowTypeId值'; return needRenderHeight ? 'required' : ''; }, }, { name: "width", label: "Width", bindings: "TextField", rules: "required", } ]
这种方式仅会在不需要渲染时跳过必填校验,height字段仍会保留在表单的取值结果中。
方式2:动态排除不展示的字段
如果你不需要在表单提交结果中保留未渲染字段的值,可以直接配置字段的exclude属性,返回true时该字段会完全不参与校验,也不会出现在最终的表单提交数据里:
fields: [ { name: "workflowTypeId", bindings: "TextField", }, { name: "height", label: "Height", bindings: "TextField", rules: "required", // 返回true时字段完全排除,不参与校验也不会出现在提交数据中 exclude: (form) => form.$('workflowTypeId').value !== '你需要展示height的对应workflowTypeId值', }, { name: "width", label: "Width", bindings: "TextField", rules: "required", } ]
注意事项
建议将判断是否渲染height字段的逻辑抽为公共复用函数,保证UI层渲染逻辑和表单校验/排除逻辑的一致性,避免两端逻辑不一致导致的bug。
内容的提问来源于stack exchange,提问作者prajeesh
相关产品推荐
相关产品推荐

