UtilsValid.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  1. using System;
  2. using System.Text;
  3. using System.Text.RegularExpressions;
  4. using System.Web;
  5. namespace CommonTool
  6. {
  7. public sealed class UtilsValid
  8. {
  9. private static readonly Regex RegPhone = new Regex("^[0-9]+[-]?[0-9]+[-]?[0-9]$");
  10. private static readonly Regex RegNumber = new Regex("^[0-9]+$");
  11. private static readonly Regex RegNumberSign = new Regex("^[+-]?[0-9]+$");
  12. private static readonly Regex RegDecimal = new Regex("^[0-9]+[.]?[0-9]+$");
  13. private static readonly Regex RegDecimalSign = new Regex("^[+-]?[0-9]+[.]?[0-9]+$"); //等价于^[+-]?\d+[.]?\d+$
  14. // ReSharper disable once UnusedMember.Local
  15. private static readonly Regex RegEmail = new Regex("^[\\w-]+@[\\w-]+\\.(com|net|org|edu|mil|tv|biz|info)$");//w 英文字母或数字的字符串,和 [a-zA-Z0-9] 语法一样
  16. private static readonly Regex RegChZn = new Regex("[\u4e00-\u9fa5]");
  17. #region 数字字符串检查
  18. public static bool IsPhone(string inputData)
  19. {
  20. Match m = RegPhone.Match(inputData);
  21. return m.Success;
  22. }
  23. /// <summary>
  24. /// 检查Request查询字符串的键值,是否是数字,最大长度限制
  25. /// </summary>
  26. /// <param name="req">Request</param>
  27. /// <param name="inputKey">Request的键值</param>
  28. /// <param name="maxLen">最大长度</param>
  29. /// <returns>返回Request查询字符串</returns>
  30. public static string FetchInputDigit(HttpRequest req, string inputKey, int maxLen)
  31. {
  32. string retVal = string.Empty;
  33. if (!string.IsNullOrEmpty(inputKey))
  34. {
  35. retVal = req.QueryString[inputKey] ?? req.Form[inputKey];
  36. if (null != retVal)
  37. {
  38. retVal = SqlText(retVal, maxLen);
  39. if (!IsNumber(retVal))
  40. retVal = string.Empty;
  41. }
  42. }
  43. return retVal ?? (string.Empty);
  44. }
  45. /// <summary>
  46. /// 是否数字字符串
  47. /// </summary>
  48. /// <param name="inputData">输入字符串</param>
  49. /// <returns></returns>
  50. public static bool IsNumber(string inputData)
  51. {
  52. Match m = RegNumber.Match(inputData);
  53. return m.Success;
  54. }
  55. /// <summary>
  56. /// 是否数字字符串 可带正负号
  57. /// </summary>
  58. /// <param name="inputData">输入字符串</param>
  59. /// <returns></returns>
  60. public static bool IsNumberSign(string inputData)
  61. {
  62. Match m = RegNumberSign.Match(inputData);
  63. return m.Success;
  64. }
  65. /// <summary>
  66. /// 是否是浮点数
  67. /// </summary>
  68. /// <param name="inputData">输入字符串</param>
  69. /// <returns></returns>
  70. public static bool IsDecimal(string inputData)
  71. {
  72. Match m = RegDecimal.Match(inputData);
  73. return m.Success;
  74. }
  75. /// <summary>
  76. /// 是否是浮点数 可带正负号
  77. /// </summary>
  78. /// <param name="inputData">输入字符串</param>
  79. /// <returns></returns>
  80. public static bool IsDecimalSign(string inputData)
  81. {
  82. Match m = RegDecimalSign.Match(inputData);
  83. return m.Success;
  84. }
  85. #endregion
  86. #region 中文检测
  87. /// <summary>
  88. /// 检测是否有中文字符
  89. /// </summary>
  90. /// <param name="inputData"></param>
  91. /// <returns></returns>
  92. public static bool IsHasChZn(string inputData)
  93. {
  94. Match m = RegChZn.Match(inputData);
  95. return m.Success;
  96. }
  97. #endregion
  98. #region 其他
  99. /// <summary>
  100. /// 检查字符串最大长度,返回指定长度的串
  101. /// </summary>
  102. /// <param name="sqlInput">输入字符串</param>
  103. /// <param name="maxLength">最大长度</param>
  104. /// <returns></returns>
  105. public static string SqlText(string sqlInput, int maxLength)
  106. {
  107. if (!string.IsNullOrEmpty(sqlInput))
  108. {
  109. sqlInput = sqlInput.Trim();
  110. if (sqlInput.Length > maxLength)//按最大长度截取字符串
  111. sqlInput = sqlInput.Substring(0, maxLength);
  112. }
  113. return sqlInput;
  114. }
  115. /// <summary>
  116. /// 字符串编码
  117. /// </summary>
  118. /// <param name="inputData"></param>
  119. /// <returns></returns>
  120. public static string HtmlEncode(string inputData)
  121. {
  122. return HttpUtility.HtmlEncode(inputData);
  123. }
  124. ///// <summary>
  125. ///// 设置Label显示Encode的字符串
  126. ///// </summary>
  127. ///// <param name="lbl"></param>
  128. ///// <param name="txtInput"></param>
  129. //public static void SetLabel(Label lbl, string txtInput)
  130. //{
  131. // lbl.Text = HtmlEncode(txtInput);
  132. //}
  133. //public static void SetLabel(Label lbl, object inputObj)
  134. //{
  135. // SetLabel(lbl, inputObj.ToString());
  136. //}
  137. //字符串清理
  138. public static string InputText(string inputString, int maxLength)
  139. {
  140. StringBuilder retVal = new StringBuilder();
  141. // 检查是否为空
  142. if (!string.IsNullOrEmpty(inputString))
  143. {
  144. inputString = inputString.Trim();
  145. //检查长度
  146. if (inputString.Length > maxLength)
  147. inputString = inputString.Substring(0, maxLength);
  148. //替换危险字符
  149. foreach (char str in inputString)
  150. {
  151. switch (str)
  152. {
  153. case '"':
  154. retVal.Append("&quot;");
  155. break;
  156. case '<':
  157. retVal.Append("&lt;");
  158. break;
  159. case '>':
  160. retVal.Append("&gt;");
  161. break;
  162. default:
  163. retVal.Append(str);
  164. break;
  165. }
  166. }
  167. retVal.Replace("'", " ");// 替换单引号
  168. }
  169. return retVal.ToString();
  170. }
  171. /// <summary>
  172. /// 转换成 HTML code
  173. /// </summary>
  174. /// <param name="str">string</param>
  175. /// <returns>string</returns>
  176. public static string Encode(string str)
  177. {
  178. str = str.Replace("&", "&amp;");
  179. str = str.Replace("'", "''");
  180. str = str.Replace("\"", "&quot;");
  181. str = str.Replace(" ", "&nbsp;");
  182. str = str.Replace("<", "&lt;");
  183. str = str.Replace(">", "&gt;");
  184. str = str.Replace("\n", "<br>");
  185. return str;
  186. }
  187. /// <summary>
  188. ///解析html成 普通文本
  189. /// </summary>
  190. /// <param name="str">string</param>
  191. /// <returns>string</returns>
  192. public static string Decode(string str)
  193. {
  194. str = str.Replace("<br>", "\n");
  195. str = str.Replace("&gt;", ">");
  196. str = str.Replace("&lt;", "<");
  197. str = str.Replace("&nbsp;", " ");
  198. str = str.Replace("&quot;", "\"");
  199. return str;
  200. }
  201. public static string SqlTextClear(string sqlText)
  202. {
  203. if (sqlText == null)
  204. {
  205. return null;
  206. }
  207. if (sqlText == "")
  208. {
  209. return "";
  210. }
  211. sqlText = sqlText.Replace(",", "");//去除,
  212. sqlText = sqlText.Replace("<", "");//去除<
  213. sqlText = sqlText.Replace(">", "");//去除>
  214. sqlText = sqlText.Replace("--", "");//去除--
  215. sqlText = sqlText.Replace("'", "");//去除'
  216. sqlText = sqlText.Replace("\"", "");//去除"
  217. sqlText = sqlText.Replace("=", "");//去除=
  218. sqlText = sqlText.Replace("%", "");//去除%
  219. sqlText = sqlText.Replace(" ", "");//去除空格
  220. return sqlText;
  221. }
  222. #endregion
  223. #region 是否由特定字符组成
  224. public static bool IsContainSameChar(string strInput)
  225. {
  226. string charInput = string.Empty;
  227. if (!string.IsNullOrEmpty(strInput))
  228. {
  229. charInput = strInput.Substring(0, 1);
  230. }
  231. return strInput != null && IsContainSameChar(strInput, charInput, strInput.Length);
  232. }
  233. public static bool IsContainSameChar(string strInput, string charInput, int lenInput)
  234. {
  235. if (string.IsNullOrEmpty(charInput))
  236. {
  237. return false;
  238. }
  239. Regex regNumber = new Regex($"^([{charInput}])+$");
  240. //Regex RegNumber = new Regex(string.Format("^([{0}]{{1}})+$", charInput,lenInput));
  241. Match m = regNumber.Match(strInput);
  242. return m.Success;
  243. }
  244. #endregion
  245. #region 检查输入的参数是不是某些定义好的特殊字符:这个方法目前用于密码输入的安全检查
  246. /// <summary>
  247. /// 检查输入的参数是不是某些定义好的特殊字符:这个方法目前用于密码输入的安全检查
  248. /// </summary>
  249. public static bool IsContainSpecChar(string strInput)
  250. {
  251. string[] list = { "123456", "654321" };
  252. bool result = new bool();
  253. foreach (string str in list)
  254. {
  255. if (strInput == str)
  256. {
  257. result = true;
  258. break;
  259. }
  260. }
  261. return result;
  262. }
  263. #endregion
  264. public static bool IsIdCard(string idNum, string birthdayYear, int gender)
  265. {
  266. string input = idNum;
  267. string str2 = "";
  268. string s = "";
  269. int length = input.Length;
  270. if ((length == 15) && (length == 0x12))
  271. {
  272. string pattern = "";
  273. switch (length)
  274. {
  275. case 15:
  276. pattern = "/d{15}";
  277. str2 = "19" + input.Substring(6, 2);
  278. s = input.Substring(14, 1);
  279. break;
  280. case 0x12:
  281. pattern = "/d{17}[0-9x]";
  282. str2 = input.Substring(6, 4);
  283. s = input.Substring(0x10, 1);
  284. break;
  285. }
  286. Regex regex = new Regex(pattern, RegexOptions.Singleline | RegexOptions.IgnoreCase);
  287. if (!regex.Match(input).Success)
  288. {
  289. return false;
  290. }
  291. if ((birthdayYear.Length > 0) && (birthdayYear != str2))
  292. {
  293. return false;
  294. }
  295. if (gender == -1)
  296. {
  297. return true;
  298. }
  299. if ((int.Parse(s) % 2) == 0)
  300. {
  301. if (gender != 0)
  302. {
  303. return false;
  304. }
  305. return false;
  306. }
  307. if (gender != 1)
  308. {
  309. return false;
  310. }
  311. }
  312. return false;
  313. }
  314. #region 验证是不是正常字符 字母,数字,下划线的组合
  315. /**/
  316. /// <summary>
  317. /// 验证是不是正常字符 字母,数字,下划线的组合
  318. /// </summary>
  319. /// <param name="source"></param>
  320. /// <returns></returns>
  321. public static bool IsNormalChar(string source)
  322. {
  323. return Regex.IsMatch(source, @"[wd_]+", RegexOptions.IgnoreCase);
  324. }
  325. #endregion
  326. #region 中文
  327. /**/
  328. /// <summary>
  329. /// 中文
  330. /// </summary>
  331. /// <param name="source"></param>
  332. /// <returns></returns>
  333. public static bool IsChinese(string source)
  334. {
  335. return Regex.IsMatch(source, @"^[u4e00-u9fa5]+$", RegexOptions.IgnoreCase);
  336. }
  337. public static bool HasChinese(string source)
  338. {
  339. return Regex.IsMatch(source, @"[u4e00-u9fa5]+", RegexOptions.IgnoreCase);
  340. }
  341. #endregion
  342. #region 邮政编码 6个数字
  343. /**/
  344. /// <summary>
  345. /// 邮政编码 6个数字
  346. /// </summary>
  347. /// <param name="source"></param>
  348. /// <returns></returns>
  349. public static bool IsPostCode(string source)
  350. {
  351. return Regex.IsMatch(source, @"^d{6}$", RegexOptions.IgnoreCase);
  352. }
  353. #endregion
  354. #region 是不是中国电话,格式010-85849685
  355. /**/
  356. /// <summary>
  357. /// 是不是中国电话,格式010-85849685
  358. /// </summary>
  359. /// <param name="source"></param>
  360. /// <returns></returns>
  361. public static bool IsTel(string source)
  362. {
  363. return Regex.IsMatch(source, @"^d{3,4}-?d{6,8}$", RegexOptions.IgnoreCase);
  364. }
  365. #endregion
  366. #region 看字符串的长度是不是在限定数之间 一个中文为两个字符
  367. /**/
  368. /// <summary>
  369. /// 看字符串的长度是不是在限定数之间 一个中文为两个字符
  370. /// </summary>
  371. /// <param name="source">字符串</param>
  372. /// <param name="begin">大于等于</param>
  373. /// <param name="end">小于等于</param>
  374. /// <returns></returns>
  375. public static bool IsLengthStr(string source, int begin, int end)
  376. {
  377. int length = Regex.Replace(source, @"[^x00-xff]", "OK").Length;
  378. if ((length <= begin) && (length >= end))
  379. {
  380. return false;
  381. }
  382. return true;
  383. }
  384. #endregion
  385. #region 验证邮箱验证邮箱
  386. /**/
  387. /// <summary>
  388. /// 验证邮箱
  389. /// </summary>
  390. /// <param name="source"></param>
  391. /// <returns></returns>
  392. public static bool IsEmail(string source)
  393. {
  394. return Regex.IsMatch(source, @"^[A-Za-z0-9](([_.-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([.-]?[a-zA-Z0-9]+)*).([A-Za-z]{2,})$", RegexOptions.IgnoreCase);
  395. }
  396. public static bool HasEmail(string source)
  397. {
  398. return Regex.IsMatch(source, @"[A-Za-z0-9](([_.-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([.-]?[a-zA-Z0-9]+)*).([A-Za-z]{2,})", RegexOptions.IgnoreCase);
  399. }
  400. #endregion
  401. #region 验证网址
  402. /**/
  403. /// <summary>
  404. /// 验证网址
  405. /// </summary>
  406. /// <param name="source"></param>
  407. /// <returns></returns>
  408. public static bool IsUrl(string source)
  409. {
  410. return Regex.IsMatch(source, @"^(((file|gopher|news|nntp|telnet|http|ftp|https|ftps|sftp)://)|(www.))+(([a-zA-Z0-9._-]+.[a-zA-Z]{2,6})|([0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}))(/[a-zA-Z0-9&amp;%_./-~-]*)?$", RegexOptions.IgnoreCase);
  411. }
  412. public static bool HasUrl(string source)
  413. {
  414. return Regex.IsMatch(source, @"(((file|gopher|news|nntp|telnet|http|ftp|https|ftps|sftp)://)|(www.))+(([a-zA-Z0-9._-]+.[a-zA-Z]{2,6})|([0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}))(/[a-zA-Z0-9&amp;%_./-~-]*)?", RegexOptions.IgnoreCase);
  415. }
  416. #endregion
  417. #region 验证日期
  418. /**/
  419. /// <summary>
  420. /// 验证日期
  421. /// </summary>
  422. /// <param name="source"></param>
  423. /// <returns></returns>
  424. public static bool IsDateTime(string source)
  425. {
  426. try
  427. {
  428. // ReSharper disable once UnusedVariable
  429. var time = Convert.ToDateTime(source);
  430. return true;
  431. }
  432. catch
  433. {
  434. return false;
  435. }
  436. }
  437. #endregion
  438. #region 验证手机号
  439. /**/
  440. /// <summary>
  441. /// 验证手机号
  442. /// </summary>
  443. /// <param name="source"></param>
  444. /// <returns></returns>
  445. public static bool IsMobile(string source)
  446. {
  447. return Regex.IsMatch(source, @"^1[35]d{9}$", RegexOptions.IgnoreCase);
  448. }
  449. public static bool HasMobile(string source)
  450. {
  451. return Regex.IsMatch(source, @"1[35]d{9}", RegexOptions.IgnoreCase);
  452. }
  453. #endregion
  454. #region 验证IP
  455. /**/
  456. /// <summary>
  457. /// 验证IP
  458. /// </summary>
  459. /// <param name="source"></param>
  460. /// <returns></returns>
  461. public static bool IsIp(string source)
  462. {
  463. return Regex.IsMatch(source, @"^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]).(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0).(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0).(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$", RegexOptions.IgnoreCase);
  464. }
  465. public static bool HasIp(string source)
  466. {
  467. return Regex.IsMatch(source, @"(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]).(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0).(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0).(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])", RegexOptions.IgnoreCase);
  468. }
  469. #endregion
  470. #region 验证身份证是否有效
  471. /**/
  472. /// <summary>
  473. /// 验证身份证是否有效
  474. /// </summary>
  475. /// <param name="id"></param>
  476. /// <returns></returns>
  477. public static bool IsIdCard(string id)
  478. {
  479. if (id.Length == 18)
  480. {
  481. bool check = IsIdCard18(id);
  482. return check;
  483. }
  484. else if (id.Length == 15)
  485. {
  486. bool check = IsIdCard15(id);
  487. return check;
  488. }
  489. else
  490. {
  491. return false;
  492. }
  493. }
  494. public static bool IsIdCard18(string id)
  495. {
  496. long n;
  497. if (long.TryParse(id.Remove(17), out n) == false || n < Math.Pow(10, 16) || long.TryParse(id.Replace('x', '0').Replace('X', '0'), out n) == false)
  498. {
  499. return false;//数字验证
  500. }
  501. string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
  502. if (address.IndexOf(id.Remove(2), StringComparison.Ordinal) == -1)
  503. {
  504. return false;//省份验证
  505. }
  506. string birth = id.Substring(6, 8).Insert(6, "-").Insert(4, "-");
  507. DateTime time;
  508. if (DateTime.TryParse(birth, out time) == false)
  509. {
  510. return false;//生日验证
  511. }
  512. string[] arrVarifyCode = ("1,0,x,9,8,7,6,5,4,3,2").Split(',');
  513. string[] wi = ("7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").Split(',');
  514. char[] ai = id.Remove(17).ToCharArray();
  515. int sum = 0;
  516. for (int i = 0; i < 17; i++)
  517. {
  518. sum += int.Parse(wi[i]) * int.Parse(ai[i].ToString());
  519. }
  520. int y;
  521. Math.DivRem(sum, 11, out y);
  522. if (arrVarifyCode[y] != id.Substring(17, 1).ToLower())
  523. {
  524. return false;//校验码验证
  525. }
  526. return true;//符合GB11643-1999标准
  527. }
  528. public static bool IsIdCard15(string id)
  529. {
  530. long n;
  531. if (long.TryParse(id, out n) == false || n < Math.Pow(10, 14))
  532. {
  533. return false;//数字验证
  534. }
  535. string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
  536. if (address.IndexOf(id.Remove(2), StringComparison.Ordinal) == -1)
  537. {
  538. return false;//省份验证
  539. }
  540. string birth = id.Substring(6, 6).Insert(4, "-").Insert(2, "-");
  541. DateTime time;
  542. if (DateTime.TryParse(birth, out time) == false)
  543. {
  544. return false;//生日验证
  545. }
  546. return true;//符合15位身份证标准
  547. }
  548. #endregion
  549. #region 是不是Int型的
  550. /**/
  551. /// <summary>
  552. /// 是不是Int型的
  553. /// </summary>
  554. /// <param name="source"></param>
  555. /// <returns></returns>
  556. public static bool IsInt(string source)
  557. {
  558. Regex regex = new Regex(@"^(-){0,1}d+$");
  559. if (regex.Match(source).Success)
  560. {
  561. if ((long.Parse(source) > 0x7fffffffL) || (long.Parse(source) < -2147483648L))
  562. {
  563. return false;
  564. }
  565. return true;
  566. }
  567. return false;
  568. }
  569. #endregion
  570. }
  571. }