You need to enable JavaScript to run this app. 如何复用Yup验证schema 解决Sonar扫描检测到的代码重复率过高问题
优惠活动
大模型
产品
解决方案
定价
更多

如何复用Yup验证schema 解决Sonar扫描检测到的代码重复率过高问题

Yup 公共验证规则复用落地方案

直接抽离公共验证逻辑到独立的公共文件即可,Yup 本身支持规则的拆分、组合、扩展,不需要改动现有 Formik 的使用逻辑。

第一步:新建公共字段规则文件

在项目公共工具目录下新建yupCommonFields.js,统一存放所有高频字段的基础验证规则:

import * as yup from 'yup';
import Labels from '你的Labels常量文件路径';

// 单个字段的基础规则直接导出
export const firmName = yup.string().label(Labels.FIRM).max(255);
export const phone = yup.string().label(Labels.PHONE).matches(/^1[3-9]\d{9}$/, '手机号格式错误');
export const realName = yup.string().label(Labels.REAL_NAME).min(2).max(20);
export const account = yup.string().label(Labels.ACCOUNT).matches(/^[a-zA-Z0-9_]{5,20}$/, '账号仅支持字母、数字、下划线,长度5-20位');

第二步:业务表单中直接复用规则

各个表单的schema.js导入需要的公共规则直接使用即可,独有字段正常写自有规则:

import * as yup from 'yup';
import { firmName, phone, realName } from '@/utils/yupCommonFields';

const schema = yup.object().shape({
  // 直接复用公共规则
  firmName,
  phone,
  realName,
  // 表单独有字段正常定义
  businessLicense: yup.string().required('请上传营业执照')
});

export default schema;

扩展场景适配

场景1:公共字段需要新增临时规则(如必填、自定义错误提示)

可直接对已有的公共规则做链式扩展,不会影响其他场景的复用:

const schema = yup.object().shape({
  // 复用基础规则的同时新增必填要求和自定义提示
  firmName: firmName.required('请填写企业名称'),
  phone: phone.required('请填写联系人手机号')
});

场景2:多个字段固定组合出现

如果有一组字段(如联系人信息、企业资质信息)经常同时出现在多个表单中,可以直接抽离公共的规则片段:

// yupCommonFields.js 中新增组合规则
export const contactGroup = {
  contactName: realName.required('请填写联系人姓名'),
  contactPhone: phone.required('请填写联系人手机号'),
  contactEmail: yup.string().label(Labels.EMAIL).email('邮箱格式错误')
};

业务表单中直接解构使用:

const schema = yup.object().shape({
  ...contactGroup, // 直接引入一整组联系人字段规则
  firmName
});

场景3:同个字段不同场景规则差异较大

可以封装成带参数的规则生成函数,根据入参返回对应规则:

// yupCommonFields.js
export const getFirmNameRule = (options = {}) => {
  const { isRequired = false, maxLength = 255 } = options;
  let rule = yup.string().label(Labels.FIRM).max(maxLength, `企业名称最多${maxLength}个字符`);
  if (isRequired) rule = rule.required('请填写企业名称');
  return rule;
};

使用时按需传参:

const schema = yup.object().shape({
  // 必填、最大长度限制为100的场景
  firmName: getFirmNameRule({ isRequired: true, maxLength: 100 })
});

以上方案改造后,公共字段的规则仅需维护一份,改动时全局生效,同时完全解决Sonar代码重复率过高的问题,现有Formik逻辑不需要做任何调整。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 23:06:01