|
|
@@ -254,6 +254,74 @@ function video(value) {
|
|
|
*/
|
|
|
function regExp(o) {
|
|
|
return o && Object.prototype.toString.call(o) === '[object RegExp]'
|
|
|
+}
|
|
|
+
|
|
|
+/**
|
|
|
+ * 通用脱敏函数
|
|
|
+ * @param {string} content - 需要脱敏的内容(邮箱/手机号/姓名)
|
|
|
+ * @param {number} [type=1] - 脱敏类型:1-邮箱(默认),2-手机,3-姓名
|
|
|
+ * @returns {string} 脱敏后的内容,不符合规则返回原内容
|
|
|
+ */
|
|
|
+function desensitizeContent(content, type = 1) {
|
|
|
+ // 基础校验:内容为空或非字符串直接返回原内容
|
|
|
+ if (!content || typeof content !== 'string') {
|
|
|
+ return content;
|
|
|
+ }
|
|
|
+
|
|
|
+ // 去除首尾空格
|
|
|
+ const trimContent = content.trim();
|
|
|
+
|
|
|
+ switch (type) {
|
|
|
+ // 1 - 邮箱脱敏
|
|
|
+ case 1: {
|
|
|
+ // 邮箱基本校验:包含@,且@前后有内容,总长度至少5位(如a@b.c)
|
|
|
+ const emailReg = /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/;
|
|
|
+ if (!emailReg.test(trimContent) || trimContent.length < 5) {
|
|
|
+ return content; // 不符合邮箱格式返回原内容
|
|
|
+ }
|
|
|
+ // 拆分邮箱:用户名@域名
|
|
|
+ const [username, domain] = trimContent.split('@');
|
|
|
+ // 用户名保留前2位,不足2位则保留1位,其余用*代替
|
|
|
+ const safeUsername = username.length > 2
|
|
|
+ ? username.substring(0, 2) + '*'.repeat(username.length - 2)
|
|
|
+ : username.substring(0, 1) + '*'.repeat(username.length - 1);
|
|
|
+ return `${safeUsername}@${domain}`;
|
|
|
+ }
|
|
|
+
|
|
|
+ // 2 - 手机号脱敏
|
|
|
+ case 2: {
|
|
|
+ // 手机号基本校验:11位数字,以1开头
|
|
|
+ const phoneReg = /^1\d{10}$/;
|
|
|
+ if (!phoneReg.test(trimContent) || trimContent.length !== 11) {
|
|
|
+ return content; // 不符合手机号格式返回原内容
|
|
|
+ }
|
|
|
+ // 保留前3位和后4位,中间4位用*代替
|
|
|
+ return trimContent.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
|
|
|
+ }
|
|
|
+
|
|
|
+ // 3 - 姓名脱敏
|
|
|
+ case 3: {
|
|
|
+ const nameLength = trimContent.length;
|
|
|
+ // 姓名长度校验:至少1位,最多6位(常规姓名长度)
|
|
|
+ if (nameLength < 1 || nameLength > 6) {
|
|
|
+ return content;
|
|
|
+ }
|
|
|
+ // 单字姓名:直接返回
|
|
|
+ if (nameLength === 1) {
|
|
|
+ return trimContent;
|
|
|
+ }
|
|
|
+ // 双字姓名:保留首字,第二个字用*代替(如:李*)
|
|
|
+ if (nameLength === 2) {
|
|
|
+ return trimContent.substring(0, 1) + '*';
|
|
|
+ }
|
|
|
+ // 三字及以上:保留首尾字,中间用*代替(如:张*三、王**明)
|
|
|
+ return trimContent.substring(0, 1) + '*'.repeat(nameLength - 2) + trimContent.substring(nameLength - 1);
|
|
|
+ }
|
|
|
+
|
|
|
+ // 未知类型:返回原内容
|
|
|
+ default:
|
|
|
+ return content;
|
|
|
+ }
|
|
|
}
|
|
|
|
|
|
export default {
|
|
|
@@ -285,5 +353,6 @@ export default {
|
|
|
video,
|
|
|
image,
|
|
|
regExp,
|
|
|
- string
|
|
|
+ string,
|
|
|
+ desensitizeContent
|
|
|
}
|