You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

mxGraph验证时如何获取错误信息字符串而非弹窗提示

解决mxGraph验证错误字符串获取问题

问题根源

你当前调用getEdgeValidationError的方式未触发完整的多重性校验逻辑,且mxGraph默认通过validationAlert方法弹出alert展示错误,单独调用getEdgeValidationError只会返回null。

可行解决方案

方案1:重写validationAlert拦截错误

替换默认的alert弹窗逻辑,直接获取并处理错误字符串:

// 覆盖默认验证弹窗方法
this.graph.validationAlert = function(message) {
  console.log('验证错误:', message);
  // 可将message存入自定义变量供后续业务使用
  // 例如:this.currentValidationError = message;
};

配置后,当多重性校验触发错误时,会自动执行你定义的逻辑,不再弹出alert,同时能直接拿到错误字符串。

方案2:手动触发完整校验流程

若需主动校验某条边,调用graph.validateEdge方法执行完整校验(而非直接调用getEdgeValidationError):

// 假设mxCell为目标边实例
if (mxCell.isEdge()) {
  const source = this.graph.getModel().getTerminal(mxCell, true);
  const target = this.graph.getModel().getTerminal(mxCell, false);
  // 执行完整边校验并获取错误信息
  const error = this.graph.validateEdge(mxCell, source, target);
  console.log('error', error);
}

validateEdge内部会触发多重性规则校验逻辑,能正确返回对应的错误字符串。

额外注意事项

  • 确保多重性规则中'Source'、'Target'与实际单元格的样式名(style)或类型匹配,否则校验逻辑不会触发。
  • 若需在边创建/修改时自动校验,可监听mxEvent.CELL_CONNECTED事件:
this.graph.addListener(mxEvent.CELL_CONNECTED, (sender, evt) => {
  const edge = evt.getProperty('edge');
  if (edge.isEdge()) {
    const source = this.graph.getModel().getTerminal(edge, true);
    const target = this.graph.getModel().getTerminal(edge, false);
    const error = this.graph.validateEdge(edge, source, target);
    error && console.log('验证错误:', error);
  }
});

内容的提问来源于stack exchange,提问作者omrsfylmz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 05:45:04