Browse Source

!112 add methods
Merge pull request !112 from lwl666/v5-dev

Looly 5 years ago
parent
commit
ec0f837037

+ 10 - 1
hutool-core/src/main/java/cn/hutool/core/lang/PatternPool.java

@@ -1,12 +1,14 @@
 package cn.hutool.core.lang;
 
+import java.util.ArrayList;
+import java.util.List;
 import java.util.regex.Pattern;
 
 import cn.hutool.core.util.ReUtil;
 
 /**
  * 常用正则表达式集合
- * 
+ *
  * @author Looly
  *
  */
@@ -65,6 +67,13 @@ public class PatternPool {
 			"([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领]\\d{3}\\d{1,3}[领])|" +
 			"([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳使领]))$");
 
+
+	/**  社会统一信用代码 */
+	public static final String CREDIT_CODE = "^[A-Z0-9]{18}$";
+
+	public static final String BASE_CODE_REGEX = "[0-9A-Y]{18}";
+
+
 	// -------------------------------------------------------------------------------------------------------------------------------------------------------------------
 	/** Pattern池 */
 	private static final SimpleCache<RegexWithFlag, Pattern> POOL = new SimpleCache<>();

+ 48 - 0
hutool-core/src/main/java/cn/hutool/core/lang/Validator.java

@@ -8,6 +8,8 @@ import cn.hutool.core.util.ReUtil;
 import cn.hutool.core.util.StrUtil;
 
 import java.net.MalformedURLException;
+import java.util.ArrayList;
+import java.util.List;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 
@@ -88,6 +90,17 @@ public class Validator {
 	public final static Pattern PLATE_NUMBER = PatternPool.PLATE_NUMBER;
 
 	/**
+	 * 社会统一信用代码
+	 */
+	public static final List<Character> BASE_CODES = new ArrayList<>();
+
+	public static final String BASE_CODE_STRING = "0123456789ABCDEFGHJKLMNPQRTUWXY";
+
+	public static final int[] WEIGHT = {1, 3, 9, 27, 19, 26, 16, 17, 20, 29, 25, 13, 8, 24, 10, 30, 28};
+
+	public static final char[] BASE_CODE_ARRAY = BASE_CODE_STRING.toCharArray();
+
+	/**
 	 * 给定值是否为<code>true</code>
 	 *
 	 * @param value 值
@@ -1103,4 +1116,39 @@ public class Validator {
 			throw new ValidateException(errorMsg);
 		}
 	}
+
+	/**
+	 * 简单校验统一社会信用代码
+	 * 18位(大写字母+数字)
+	 *
+	 * @param creditCode 统一社会信用代码
+	 * @return 校验结果
+	 */
+	public static boolean isCreditCodeBySimple(String creditCode) {
+		if (StrUtil.isBlank(creditCode)) {
+			return false;
+		}
+		return Pattern.matches(PatternPool.CREDIT_CODE, creditCode);
+	}
+
+	/**
+	 * 是否是有效的统一社会信用代码
+	 *
+	 * @param creditCode 统一社会信用代码
+	 * @return 校验结果
+	 */
+	public static boolean isCreditCode(String creditCode) {
+		if (StrUtil.isBlank(creditCode) || !Pattern.matches(PatternPool.BASE_CODE_REGEX, creditCode)) {
+			return false;
+		}
+		char[] businessCodeArray = creditCode.toCharArray();
+		char check = businessCodeArray[17];
+		int sum = 0, length = 17;
+		for (int i = 0; i < length; i++) {
+			char key = businessCodeArray[i];
+			sum += (BASE_CODES.indexOf(key) * WEIGHT[i]);
+		}
+		int value = 31 - sum % 31;
+		return check == BASE_CODE_ARRAY[value % 31];
+	}
 }