颐和api

ValidateHelper.cs 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. using System;
  2. using System.Text.RegularExpressions;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.IO;
  7. using Newtonsoft.Json;
  8. namespace MadRunFabric.Common
  9. {
  10. /*
  11. * https://github.com/arasatasaygin/is.js/blob/master/is.js
  12. *
  13. var regexes = {
  14. affirmative: /^(?:1|t(?:rue)?|y(?:es)?|ok(?:ay)?)$/,
  15. alphaNumeric: /^[A-Za-z0-9]+$/,
  16. caPostalCode: /^(?!.*[DFIOQU])[A-VXY][0-9][A-Z]\s?[0-9][A-Z][0-9]$/,
  17. creditCard: /^(?:(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11}))$/,
  18. dateString: /^(1[0-2]|0?[1-9])([\/-])(3[01]|[12][0-9]|0?[1-9])(?:\2)(?:[0-9]{2})?[0-9]{2}$/,
  19. email: /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i, // eslint-disable-line no-control-regex
  20. eppPhone: /^\+[0-9]{1,3}\.[0-9]{4,14}(?:x.+)?$/,
  21. hexadecimal: /^(?:0x)?[0-9a-fA-F]+$/,
  22. hexColor: /^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,
  23. ipv4: /^(?:(?:\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])\.){3}(?:\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])$/,
  24. ipv6: /^((?=.*::)(?!.*::.+::)(::)?([\dA-F]{1,4}:(:|\b)|){5}|([\dA-F]{1,4}:){6})((([\dA-F]{1,4}((?!\3)::|:\b|$))|(?!\2\3)){2}|(((2[0-4]|1\d|[1-9])?\d|25[0-5])\.?\b){4})$/i,
  25. nanpPhone: /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/,
  26. socialSecurityNumber: /^(?!000|666)[0-8][0-9]{2}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4}$/,
  27. timeString: /^(2[0-3]|[01]?[0-9]):([0-5]?[0-9]):([0-5]?[0-9])$/,
  28. ukPostCode: /^[A-Z]{1,2}[0-9RCHNQ][0-9A-Z]?\s?[0-9][ABD-HJLNP-UW-Z]{2}$|^[A-Z]{2}-?[0-9]{4}$/,
  29. url: /^(?:(?:https?|ftp):\/\/)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/\S*)?$/i,
  30. usZipCode: /^[0-9]{5}(?:-[0-9]{4})?$/
  31. };
  32. */
  33. /// <summary>
  34. /// 验证帮助类
  35. /// </summary>
  36. public static class ValidateHelper
  37. {
  38. private static readonly Regex RegNumber = new Regex("^[0-9]+$", RegexOptions.Compiled);
  39. private static readonly Regex RegNumberSign = new Regex("^[+-]?[0-9]+$", RegexOptions.Compiled);
  40. private static readonly Regex RegDecimal = new Regex("^[0-9]+[.]?[0-9]+$", RegexOptions.Compiled);
  41. private static readonly Regex RegDecimalSign = new Regex("^[+-]?[0-9]+[.]?[0-9]+$", RegexOptions.Compiled); //等价于^[+-]?\d+[.]?\d+$
  42. private static readonly Regex RegEmail = new Regex(@"^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$", RegexOptions.Compiled);//w 英文字母或数字的字符串,和 [a-zA-Z0-9] 语法一样
  43. private static readonly Regex RegCHZN = new Regex("[\u4e00-\u9fa5]", RegexOptions.Compiled);
  44. /// <summary>
  45. /// 判断是否是邮件地址,来自nop的方法
  46. /// </summary>
  47. /// <param name="s"></param>
  48. /// <returns></returns>
  49. public static bool IsEmail(string s)
  50. {
  51. return IsPlumpString(s) && RegexHelper.IsMatch(s, @"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$");
  52. }
  53. /// <summary>
  54. /// 判断是不是url
  55. /// </summary>
  56. /// <param name="s"></param>
  57. /// <returns></returns>
  58. public static bool IsURL(string s)
  59. {
  60. return IsPlumpString(s) && RegexHelper.IsMatch(s, @"[a-zA-z]+://[^s]*");
  61. }
  62. /// <summary>
  63. /// 是手机号
  64. /// </summary>
  65. /// <param name="s"></param>
  66. /// <returns></returns>
  67. public static bool IsMobilePhone(string s)
  68. {
  69. return IsPlumpString(s) && RegexHelper.IsMatch(s, @"^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$");
  70. }
  71. /// <summary>
  72. /// 是否为固话号
  73. /// </summary>
  74. public static bool IsPhone(string s)
  75. {
  76. return IsPlumpString(s) && RegexHelper.IsMatch(s, @"^(\d{3,4}-?)?\d{7,8}$");
  77. }
  78. /// <summary>
  79. /// 是否是域名
  80. /// </summary>
  81. /// <param name="s"></param>
  82. /// <returns></returns>
  83. public static bool IsDomain(string s)
  84. {
  85. return IsPlumpString(s) && RegexHelper.IsMatch(s, @"^[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+$");
  86. }
  87. /// <summary>
  88. /// 是否是中文
  89. /// </summary>
  90. /// <param name="s"></param>
  91. /// <returns></returns>
  92. public static bool IsChinese(string s)
  93. {
  94. return IsPlumpString(s) && RegexHelper.IsMatch(s, @"^[\u4e00-\u9fa5]{0,}$");
  95. }
  96. /// <summary>
  97. /// 是否是身份证号
  98. /// </summary>
  99. /// <param name="s"></param>
  100. /// <returns></returns>
  101. public static bool IsIDCardNo(string s)
  102. {
  103. return IsPlumpString(s) && RegexHelper.IsMatch(s, @"^(^\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$");
  104. }
  105. /// <summary>
  106. /// 是否为日期
  107. /// </summary>
  108. public static bool IsDate(string s)
  109. {
  110. //return IsPlumpString(s) && RegexHelper.IsMatch(s, @"(\d{4})-(\d{1,2})-(\d{1,2})");
  111. return DateTime.TryParse(s, out var re);
  112. }
  113. /// <summary>
  114. /// 是否是IP
  115. /// </summary>
  116. public static bool IsIP(string s) =>
  117. IsPlumpString(s) && RegexHelper.IsMatch(s, @"\d+\.\d+\.\d+\.\d+");
  118. public static bool IsIPv4(string s) =>
  119. IsPlumpString(s) && RegexHelper.IsMatch(s, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
  120. public static bool IsIPv6(string s) =>
  121. IsPlumpString(s) && RegexHelper.IsMatch(s, @"/^((?=.*::)(?!.*::.+::)(::)?([\dA-F]{1,4}:(:|\b)|){5}|([\dA-F]{1,4}:){6})((([\dA-F]{1,4}((?!\3)::|:\b|$))|(?!\2\3)){2}|(((2[0-4]|1\d|[1-9])?\d|25[0-5])\.?\b){4})$/i");
  122. /// <summary>
  123. /// 是否是时间
  124. /// </summary>
  125. /// <param name="s"></param>
  126. /// <returns></returns>
  127. public static bool IsTime(string s)
  128. {
  129. return IsPlumpString(s) && RegexHelper.IsMatch(s, @"^(([0-1]?[0-9])|([2][0-3])):([0-5]?[0-9])(:([0-5]?[0-9]))?$");
  130. }
  131. /// <summary>
  132. /// 数字或者字母
  133. /// </summary>
  134. /// <param name="s"></param>
  135. /// <returns></returns>
  136. public static bool IsNUMBER_OR_CHAR(string s)
  137. {
  138. return IsPlumpString(s) && RegexHelper.IsMatch(s, @"^[A-Za-z0-9]{4,40}$");
  139. }
  140. /// <summary>
  141. /// 是否是数字
  142. /// </summary>
  143. /// <param name="s"></param>
  144. /// <returns></returns>
  145. public static bool IsNumber(string s)
  146. {
  147. return IsPlumpString(s) && RegexHelper.IsMatch(s, @"^[0-9]*$");
  148. }
  149. /// <summary>
  150. /// 是否是数值(包括整数和小数)
  151. /// </summary>
  152. public static bool IsFloat(string s)
  153. {
  154. return float.TryParse(s, out var re);
  155. }
  156. /// <summary>
  157. /// 是否是double
  158. /// </summary>
  159. /// <param name="s"></param>
  160. /// <returns></returns>
  161. public static bool IsDouble(string s)
  162. {
  163. return double.TryParse(s, out var re);
  164. }
  165. /// <summary>
  166. /// 判断是数字,空返回false(前面可以带负号)
  167. /// </summary>
  168. /// <param name="s"></param>
  169. /// <returns></returns>
  170. public static bool IsInt(string s)
  171. {
  172. return int.TryParse(s, out var re);
  173. }
  174. /// <summary>
  175. /// 判断是字母,空返回false
  176. /// </summary>
  177. /// <param name="s"></param>
  178. /// <returns></returns>
  179. public static bool IsChar(string s)
  180. {
  181. if (!IsPlumpString(s)) { return false; }
  182. return s.ToArray().All(x => (x >= 'a' && x <= 'z') || (x >= 'A' && x <= 'Z'));
  183. }
  184. /// <summary>
  185. /// 判断是否是中文字符串
  186. /// </summary>
  187. /// <param name="str"></param>
  188. /// <returns></returns>
  189. public static bool IsChineaseStr(string str)
  190. {
  191. if (!IsPlumpString(str))
  192. {
  193. return false;
  194. }
  195. return str.ToArray().All(x => x >= 0x4e00 && x <= 0x9fbb);
  196. }
  197. /// <summary>
  198. /// 简单判断是否是json,不一定全部正确
  199. /// </summary>
  200. /// <param name="json"></param>
  201. /// <returns></returns>
  202. public static bool IsJson(string json)
  203. {
  204. try
  205. {
  206. return JsonConvert.DeserializeObject(json) != null;
  207. }
  208. catch
  209. {
  210. return false;
  211. }
  212. }
  213. /// <summary>
  214. /// 检查颜色值是否为3/6位的合法颜色只支持#ffffff格式,rgb(0,0,0)格式不能验证通过
  215. /// </summary>
  216. /// <param name="color">待检查的颜色</param>
  217. /// <returns></returns>
  218. public static bool IsColor(string color)
  219. {
  220. if (!IsPlumpString(color)) { return false; }
  221. color = color.Trim();
  222. if (color.StartsWith("#")) { return false; }
  223. color = color.Trim('#');
  224. if (color.Length != 3 && color.Length != 6) { return false; }
  225. //不包含0-9 a-f以外的字符
  226. if (!RegexHelper.IsMatch(color, "[^0-9a-f]", RegexOptions.IgnoreCase))
  227. {
  228. return true;
  229. }
  230. return false;
  231. }
  232. public static readonly string[] ImageExtesions = new string[] { ".jpg", ".png", ".gif", ".bmp", ".jpeg" };
  233. /// <summary>
  234. /// 是否是图片
  235. /// </summary>
  236. /// <param name="urlOrPathOrName"></param>
  237. /// <returns></returns>
  238. public static bool IsImage(string urlOrPathOrName)
  239. {
  240. urlOrPathOrName = ConvertHelper.GetString(urlOrPathOrName).Trim().ToLower();
  241. foreach (var ext in ImageExtesions)
  242. {
  243. if (urlOrPathOrName.EndsWith(ext)) { return true; }
  244. }
  245. return false;
  246. }
  247. /// <summary>
  248. /// 判断文件流是否为UTF8字符集
  249. /// </summary>
  250. /// <param name="stream">文件流</param>
  251. /// <returns>判断结果</returns>
  252. private static bool IsUTF8(FileStream stream)
  253. {
  254. byte cOctets = 0; // octets to go in this UTF-8 encoded character
  255. byte chr;
  256. bool bAllAscii = true;
  257. for (int i = 0; i < stream.Length; ++i)
  258. {
  259. chr = (byte)stream.ReadByte();
  260. if ((chr & 0x80) != 0) { bAllAscii = false; }
  261. if (cOctets == 0)
  262. {
  263. if (chr >= 0x80)
  264. {
  265. do
  266. {
  267. chr <<= 1;
  268. cOctets++;
  269. }
  270. while ((chr & 0x80) != 0);
  271. cOctets--;
  272. if (cOctets == 0) { return false; }
  273. }
  274. }
  275. else
  276. {
  277. if ((chr & 0xC0) != 0x80) { return false; }
  278. cOctets--;
  279. }
  280. }
  281. if (cOctets > 0)
  282. {
  283. return false;
  284. }
  285. if (bAllAscii)
  286. {
  287. return false;
  288. }
  289. return true;
  290. }
  291. #region 判断是否是空数据
  292. /// <summary>
  293. /// 判断是否是有值的list
  294. /// </summary>
  295. public static bool IsPlumpList<T>(IEnumerable<T> list) => list?.Any() ?? false;
  296. /// <summary>
  297. /// 包含长度大于0的item,并把他们找出来
  298. /// </summary>
  299. public static bool IsPlumpListAfterFilterMeaninglessData(IEnumerable<string> list, out List<string> filtered)
  300. {
  301. filtered = ConvertHelper.NotNullList(list).Where(x => IsPlumpString(x)).ToList();
  302. return filtered.Any();
  303. }
  304. /// <summary>
  305. /// 判断是否是有值的字典
  306. /// </summary>
  307. public static bool IsPlumpDict<K, V>(IDictionary<K, V> dict) => dict?.Any() ?? false;
  308. /// <summary>
  309. /// 去除两端空格后判断是否是非空字符串
  310. /// </summary>
  311. public static bool IsPlumpStringAfterTrim(string str) => (str?.Trim().Length ?? 0) > 0;
  312. /// <summary>
  313. /// 判断是否是非空字符串
  314. /// </summary>
  315. public static bool IsPlumpString(string str) => (str?.Length ?? 0) > 0;
  316. /// <summary>
  317. /// 判断是否都是非空字符串
  318. /// </summary>
  319. public static bool IsAllPlumpString(params string[] strs)
  320. {
  321. if (!IsPlumpList(strs)) { throw new Exception("至少需要一个参数"); }
  322. return strs.All(x => IsPlumpString(x));
  323. }
  324. /// <summary>
  325. /// 判断数组里至少有一个非空字符串
  326. /// </summary>
  327. public static bool IsAnyPlumpString(params string[] strs)
  328. {
  329. if (!IsPlumpList(strs)) { throw new Exception("至少需要一个参数"); }
  330. return strs.Any(x => IsPlumpString(x));
  331. }
  332. #endregion
  333. /// <summary>
  334. /// 判断字符串的长度是否在范围之内,str可以为空
  335. /// </summary>
  336. public static bool IsLenInRange(string str, int min, int max)
  337. {
  338. var len = str?.Length ?? 0;
  339. return len >= min && len <= max;
  340. }
  341. /// <summary>
  342. /// 判断一个对象是否是某个类型
  343. /// </summary>
  344. public static bool Is<T>(object obj)
  345. {
  346. return obj != null && obj is T;
  347. }
  348. /// <summary>
  349. /// 判断是相同引用
  350. /// </summary>
  351. public static bool IsReferenceEquals(object obj1, object obj2)
  352. {
  353. return object.ReferenceEquals(obj1, obj2);
  354. }
  355. /// <summary>
  356. /// 两个json有相同的结构
  357. /// </summary>
  358. /// <param name="tuple"></param>
  359. /// <returns></returns>
  360. public static bool SameJsonStructure(this (string, string) tuple)
  361. {
  362. return JsonHelper.HasSameStructure(tuple.Item1, tuple.Item2);
  363. }
  364. }
  365. }