PageRenderTime 66ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 0ms

/DotNet.Framework.Common/PageValidate.cs

http://dotnetcommon1.codeplex.com
C# | 775 lines | 519 code | 74 blank | 182 comment | 96 complexity | 2010003d2e10bebafb27936278e0a190 MD5 | raw file
  1. using System;
  2. using System.Text;
  3. using System.Text.RegularExpressions;
  4. using System.Web;
  5. using DotNet.Framework.Common.Helper;
  6. namespace DotNet.Framework.Common
  7. {
  8. /// <summary>
  9. /// 页面数据校验类
  10. /// 李天平
  11. /// 2004.8
  12. /// </summary>
  13. public class PageValidate
  14. {
  15. private static Regex RegPhone = new Regex("^[0-9]+[-]?[0-9]+[-]?[0-9]$");
  16. private static Regex RegNumber = new Regex("^[0-9]+$");
  17. private static Regex RegNumberSign = new Regex("^[+-]?[0-9]+$");
  18. private static Regex RegDecimal = new Regex("^[0-9]+[.]?[0-9]+$");
  19. private static Regex RegDecimalSign = new Regex("^[+-]?[0-9]+[.]?[0-9]+$"); //等价于^[+-]?\d+[.]?\d+$
  20. private static Regex RegEmail = new Regex("^[\\w-]+@[\\w-]+\\.(com|net|cn|org|edu|mil|tv|biz|info)$");//w 英文字母或数字的字符串,和 [a-zA-Z0-9] 语法一样
  21. private static Regex RegCHZN = new Regex("[\u4e00-\u9fa5]");
  22. /// <summary>
  23. /// 默认构造函数
  24. /// </summary>
  25. public PageValidate()
  26. {
  27. }
  28. #region 数字字符串检查
  29. /// <summary>
  30. /// 检查输入的字符串是否是电话类型
  31. /// </summary>
  32. /// <param name="inputData"></param>
  33. /// <returns></returns>
  34. public static bool IsPhone(string inputData)
  35. {
  36. Match m = RegPhone.Match(inputData);
  37. return m.Success;
  38. }
  39. /// <summary>
  40. /// 检查Request查询字符串的键值,是否是数字,最大长度限制
  41. /// </summary>
  42. /// <param name="req">Request</param>
  43. /// <param name="inputKey">Request的键值</param>
  44. /// <param name="maxLen">最大长度</param>
  45. /// <returns>返回Request查询字符串</returns>
  46. public static string FetchInputDigit(HttpRequest req, string inputKey, int maxLen)
  47. {
  48. string retVal = string.Empty;
  49. if (inputKey != null && inputKey != string.Empty)
  50. {
  51. retVal = req.QueryString[inputKey];
  52. if (null == retVal)
  53. retVal = req.Form[inputKey];
  54. if (null != retVal)
  55. {
  56. retVal = SqlText(retVal, maxLen);
  57. if (!IsNumber(retVal))
  58. retVal = string.Empty;
  59. }
  60. }
  61. if (retVal == null)
  62. retVal = string.Empty;
  63. return retVal;
  64. }
  65. /// <summary>
  66. /// 是否数字字符串
  67. /// </summary>
  68. /// <param name="inputData">输入字符串</param>
  69. /// <returns></returns>
  70. public static bool IsNumber(string inputData)
  71. {
  72. Match m = RegNumber.Match(inputData);
  73. return m.Success;
  74. }
  75. /// <summary>
  76. /// 是否数字字符串 可带正负号
  77. /// </summary>
  78. /// <param name="inputData">输入字符串</param>
  79. /// <returns></returns>
  80. public static bool IsNumberSign(string inputData)
  81. {
  82. Match m = RegNumberSign.Match(inputData);
  83. return m.Success;
  84. }
  85. /// <summary>
  86. /// 是否是浮点数
  87. /// </summary>
  88. /// <param name="inputData">输入字符串</param>
  89. /// <returns></returns>
  90. public static bool IsDecimal(string inputData)
  91. {
  92. Match m = RegDecimal.Match(inputData);
  93. return m.Success;
  94. }
  95. /// <summary>
  96. /// 是否是浮点数 可带正负号
  97. /// </summary>
  98. /// <param name="inputData">输入字符串</param>
  99. /// <returns></returns>
  100. public static bool IsDecimalSign(string inputData)
  101. {
  102. Match m = RegDecimalSign.Match(inputData);
  103. return m.Success;
  104. }
  105. #endregion
  106. #region 中文检测
  107. /// <summary>
  108. /// 检测是否有中文字符
  109. /// </summary>
  110. /// <param name="inputData"></param>
  111. /// <returns></returns>
  112. public static bool IsHasCHZN(string inputData)
  113. {
  114. Match m = RegCHZN.Match(inputData);
  115. return m.Success;
  116. }
  117. #endregion
  118. #region 邮件地址
  119. /// <summary>
  120. /// 是否邮件地址
  121. /// </summary>
  122. /// <param name="inputData">输入字符串</param>
  123. /// <returns></returns>
  124. public static bool IsEmail(string inputData)
  125. {
  126. Match m = RegEmail.Match(inputData);
  127. return m.Success;
  128. }
  129. #endregion
  130. #region 日期格式判断
  131. /// <summary>
  132. /// 日期格式字符串判断
  133. /// </summary>
  134. /// <param name="str"></param>
  135. /// <returns></returns>
  136. public static bool IsDateTime(string str)
  137. {
  138. try
  139. {
  140. if (!string.IsNullOrEmpty(str))
  141. {
  142. DateTime.Parse(str);
  143. return true;
  144. }
  145. else
  146. {
  147. return false;
  148. }
  149. }
  150. catch
  151. {
  152. return false;
  153. }
  154. }
  155. #endregion
  156. #region 身份证号码验证
  157. /// <summary>
  158. /// 验证身份证号码
  159. /// </summary>
  160. /// <param name="Id">身份证号码</param>
  161. /// <returns>验证成功为True,否则为False</returns>
  162. public static bool CheckIDCard(string Id)
  163. {
  164. if (Id.Length == 18)
  165. {
  166. bool check = CheckIDCard18(Id);
  167. return check;
  168. }
  169. else if (Id.Length == 15)
  170. {
  171. bool check = CheckIDCard15(Id);
  172. return check;
  173. }
  174. else
  175. {
  176. return false;
  177. }
  178. }
  179. /// <summary>
  180. /// 验证15位身份证号
  181. /// </summary>
  182. /// <param name="Id">身份证号</param>
  183. /// <returns>验证成功为True,否则为False</returns>
  184. private static bool CheckIDCard18(string Id)
  185. {
  186. long n = 0;
  187. 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)
  188. {
  189. return false;//数字验证
  190. }
  191. string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
  192. if (address.IndexOf(Id.Remove(2)) == -1)
  193. {
  194. return false;//省份验证
  195. }
  196. string birth = Id.Substring(6, 8).Insert(6, "-").Insert(4, "-");
  197. DateTime time = new DateTime();
  198. if (DateTime.TryParse(birth, out time) == false)
  199. {
  200. return false;//生日验证
  201. }
  202. string[] arrVarifyCode = ("1,0,x,9,8,7,6,5,4,3,2").Split(',');
  203. string[] Wi = ("7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").Split(',');
  204. char[] Ai = Id.Remove(17).ToCharArray();
  205. int sum = 0;
  206. for (int i = 0; i < 17; i++)
  207. {
  208. sum += int.Parse(Wi[i]) * int.Parse(Ai[i].ToString());
  209. }
  210. int y = -1;
  211. Math.DivRem(sum, 11, out y);
  212. if (arrVarifyCode[y] != Id.Substring(17, 1).ToLower())
  213. {
  214. return false;//校验码验证
  215. }
  216. return true;//符合GB11643-1999标准
  217. }
  218. /// <summary>
  219. /// 验证18位身份证号
  220. /// </summary>
  221. /// <param name="Id">身份证号</param>
  222. /// <returns>验证成功为True,否则为False</returns>
  223. private static bool CheckIDCard15(string Id)
  224. {
  225. long n = 0;
  226. if (long.TryParse(Id, out n) == false || n < Math.Pow(10, 14))
  227. {
  228. return false;//数字验证
  229. }
  230. string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
  231. if (address.IndexOf(Id.Remove(2)) == -1)
  232. {
  233. return false;//省份验证
  234. }
  235. string birth = Id.Substring(6, 6).Insert(4, "-").Insert(2, "-");
  236. DateTime time = new DateTime();
  237. if (DateTime.TryParse(birth, out time) == false)
  238. {
  239. return false;//生日验证
  240. }
  241. return true;//符合15位身份证标准
  242. }
  243. #endregion
  244. #region 其他
  245. /// <summary>
  246. /// 检查字符串最大长度,返回指定长度的串
  247. /// </summary>
  248. /// <param name="sqlInput">输入字符串</param>
  249. /// <param name="maxLength">最大长度</param>
  250. /// <returns></returns>
  251. public static string SqlText(string sqlInput, int maxLength)
  252. {
  253. if (sqlInput != null && sqlInput != string.Empty)
  254. {
  255. sqlInput = sqlInput.Trim();
  256. if (sqlInput.Length > maxLength)//按最大长度截取字符串
  257. sqlInput = sqlInput.Substring(0, maxLength);
  258. }
  259. return sqlInput;
  260. }
  261. /// <summary>
  262. /// 字符串编码
  263. /// </summary>
  264. /// <param name="inputData"></param>
  265. /// <returns></returns>
  266. public static string HtmlEncode(string inputData)
  267. {
  268. return HttpUtility.HtmlEncode(inputData);
  269. }
  270. /// <summary>
  271. /// 设置Label显示Encode的字符串
  272. /// </summary>
  273. /// <param name="lbl"></param>
  274. /// <param name="txtInput"></param>
  275. public static void SetLabel(System.Web.UI.WebControls.Label lbl, string txtInput)
  276. {
  277. lbl.Text = HtmlEncode(txtInput);
  278. }
  279. /// <summary>
  280. /// 为Label赋值
  281. /// </summary>
  282. /// <param name="lbl"></param>
  283. /// <param name="inputObj"></param>
  284. public static void SetLabel(System.Web.UI.WebControls.Label lbl, object inputObj)
  285. {
  286. SetLabel(lbl, inputObj.ToString());
  287. }
  288. /// <summary>
  289. /// 字符串清理
  290. /// </summary>
  291. /// <param name="inputString"></param>
  292. /// <param name="maxLength"></param>
  293. /// <returns></returns>
  294. public static string InputText(string inputString, int maxLength)
  295. {
  296. StringBuilder retVal = new StringBuilder();
  297. // 检查是否为空
  298. if ((inputString != null) && (inputString != String.Empty))
  299. {
  300. inputString = inputString.Trim();
  301. //检查长度
  302. if (inputString.Length > maxLength)
  303. inputString = inputString.Substring(0, maxLength);
  304. //替换危险字符
  305. for (int i = 0; i < inputString.Length; i++)
  306. {
  307. switch (inputString[i])
  308. {
  309. case '"':
  310. retVal.Append("&quot;");
  311. break;
  312. case '<':
  313. retVal.Append("&lt;");
  314. break;
  315. case '>':
  316. retVal.Append("&gt;");
  317. break;
  318. default:
  319. retVal.Append(inputString[i]);
  320. break;
  321. }
  322. }
  323. retVal.Replace("'", " ");// 替换单引号
  324. }
  325. return retVal.ToString();
  326. }
  327. /// <summary>
  328. /// 转换成 HTML code
  329. /// </summary>
  330. /// <param name="str">string</param>
  331. /// <returns>string</returns>
  332. public static string Encode(string str)
  333. {
  334. str = str.Replace("&", "&amp;");
  335. str = str.Replace("'", "''");
  336. str = str.Replace("\"", "&quot;");
  337. str = str.Replace(" ", "&nbsp;");
  338. str = str.Replace("<", "&lt;");
  339. str = str.Replace(">", "&gt;");
  340. str = str.Replace("\n", "<br>");
  341. return str;
  342. }
  343. /// <summary>
  344. ///解析html成 普通文本
  345. /// </summary>
  346. /// <param name="str">string</param>
  347. /// <returns>string</returns>
  348. public static string Decode(string str)
  349. {
  350. str = str.Replace("<br>", "\n");
  351. str = str.Replace("&gt;", ">");
  352. str = str.Replace("&lt;", "<");
  353. str = str.Replace("&nbsp;", " ");
  354. str = str.Replace("&quot;", "\"");
  355. return str;
  356. }
  357. /// <summary>
  358. /// SQL注入字符清理
  359. /// </summary>
  360. /// <param name="sqlText"></param>
  361. /// <returns></returns>
  362. public static string SqlTextClear(string sqlText)
  363. {
  364. if (sqlText == null)
  365. {
  366. return null;
  367. }
  368. if (sqlText == "")
  369. {
  370. return "";
  371. }
  372. sqlText = sqlText.Replace(",", "");//去除,
  373. sqlText = sqlText.Replace("<", "");//去除<
  374. sqlText = sqlText.Replace(">", "");//去除>
  375. sqlText = sqlText.Replace("--", "");//去除--
  376. sqlText = sqlText.Replace("'", "");//去除'
  377. sqlText = sqlText.Replace("\"", "");//去除"
  378. sqlText = sqlText.Replace("=", "");//去除=
  379. sqlText = sqlText.Replace("%", "");//去除%
  380. sqlText = sqlText.Replace(" ", "");//去除空格
  381. return sqlText;
  382. }
  383. #endregion
  384. #region 是否由特定字符组成
  385. public static bool isContainSameChar(string strInput)
  386. {
  387. string charInput = string.Empty;
  388. if (!string.IsNullOrEmpty(strInput))
  389. {
  390. charInput = strInput.Substring(0, 1);
  391. }
  392. return isContainSameChar(strInput, charInput, strInput.Length);
  393. }
  394. public static bool isContainSameChar(string strInput, string charInput, int lenInput)
  395. {
  396. if (string.IsNullOrEmpty(charInput))
  397. {
  398. return false;
  399. }
  400. else
  401. {
  402. Regex RegNumber = new Regex(string.Format("^([{0}])+$", charInput));
  403. //Regex RegNumber = new Regex(string.Format("^([{0}]{{1}})+$", charInput,lenInput));
  404. Match m = RegNumber.Match(strInput);
  405. return m.Success;
  406. }
  407. }
  408. #endregion
  409. #region 检查输入的参数是不是某些定义好的特殊字符这个方法目前用于密码输入的安全检查
  410. /// <summary>
  411. /// 检查输入的参数是不是某些定义好的特殊字符:这个方法目前用于密码输入的安全检查
  412. /// </summary>
  413. public static bool isContainSpecChar(string strInput)
  414. {
  415. string[] list = new string[] { "123456", "654321" };
  416. bool result = new bool();
  417. for (int i = 0; i < list.Length; i++)
  418. {
  419. if (strInput == list[i])
  420. {
  421. result = true;
  422. break;
  423. }
  424. }
  425. return result;
  426. }
  427. #endregion
  428. #region 验证IP地址是否合法
  429. /// <summary>
  430. /// 验证IP地址是否合法
  431. /// </summary>
  432. /// <param name="ip">要验证的IP地址</param>
  433. public static bool IsIP(string ip)
  434. {
  435. //如果为空,认为验证合格
  436. if (IsNullOrEmpty(ip))
  437. {
  438. return true;
  439. }
  440. //清除要验证字符串中的空格
  441. ip = ip.Trim();
  442. //模式字符串
  443. string pattern = @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$";
  444. //验证
  445. return RegexHelper.IsMatch(ip, pattern);
  446. }
  447. #endregion
  448. #region 验证是否为整数
  449. /// <summary>
  450. /// 验证是否为整数 如果为空,认为验证不合格 返回false
  451. /// </summary>
  452. /// <param name="number">要验证的整数</param>
  453. public static bool IsInt(string number)
  454. {
  455. //如果为空,认为验证不合格
  456. if (IsNullOrEmpty(number))
  457. {
  458. return false;
  459. }
  460. //清除要验证字符串中的空格
  461. number = number.Trim();
  462. //模式字符串
  463. string pattern = @"^[0-9]+[0-9]*$";
  464. //验证
  465. return RegexHelper.IsMatch(number, pattern);
  466. }
  467. #endregion
  468. #region 验证日期是否合法
  469. /// <summary>
  470. /// 验证日期是否合法,对不规则的作了简单处理
  471. /// </summary>
  472. /// <param name="date">日期</param>
  473. public static bool IsDate(ref string date)
  474. {
  475. //如果为空,认为验证合格
  476. if (IsNullOrEmpty(date))
  477. {
  478. return true;
  479. }
  480. //清除要验证字符串中的空格
  481. date = date.Trim();
  482. //替换\
  483. date = date.Replace(@"\", "-");
  484. //替换/
  485. date = date.Replace(@"/", "-");
  486. //如果查找到汉字"今",则认为是当前日期
  487. if (date.IndexOf("今") != -1)
  488. {
  489. date = DateTime.Now.ToString();
  490. }
  491. try
  492. {
  493. //用转换测试是否为规则的日期字符
  494. date = Convert.ToDateTime(date).ToString("d");
  495. return true;
  496. }
  497. catch
  498. {
  499. //如果日期字符串中存在非数字,则返回false
  500. if (!IsInt(date))
  501. {
  502. return false;
  503. }
  504. #region 对纯数字进行解析
  505. //对8位纯数字进行解析
  506. if (date.Length == 8)
  507. {
  508. //获取年月日
  509. string year = date.Substring(0, 4);
  510. string month = date.Substring(4, 2);
  511. string day = date.Substring(6, 2);
  512. //验证合法性
  513. if (Convert.ToInt32(year) < 1900 || Convert.ToInt32(year) > 2100)
  514. {
  515. return false;
  516. }
  517. if (Convert.ToInt32(month) > 12 || Convert.ToInt32(day) > 31)
  518. {
  519. return false;
  520. }
  521. //拼接日期
  522. date = Convert.ToDateTime(year + "-" + month + "-" + day).ToString("d");
  523. return true;
  524. }
  525. //对6位纯数字进行解析
  526. if (date.Length == 6)
  527. {
  528. //获取年月
  529. string year = date.Substring(0, 4);
  530. string month = date.Substring(4, 2);
  531. //验证合法性
  532. if (Convert.ToInt32(year) < 1900 || Convert.ToInt32(year) > 2100)
  533. {
  534. return false;
  535. }
  536. if (Convert.ToInt32(month) > 12)
  537. {
  538. return false;
  539. }
  540. //拼接日期
  541. date = Convert.ToDateTime(year + "-" + month).ToString("d");
  542. return true;
  543. }
  544. //对5位纯数字进行解析
  545. if (date.Length == 5)
  546. {
  547. //获取年月
  548. string year = date.Substring(0, 4);
  549. string month = date.Substring(4, 1);
  550. //验证合法性
  551. if (Convert.ToInt32(year) < 1900 || Convert.ToInt32(year) > 2100)
  552. {
  553. return false;
  554. }
  555. //拼接日期
  556. date = year + "-" + month;
  557. return true;
  558. }
  559. //对4位纯数字进行解析
  560. if (date.Length == 4)
  561. {
  562. //获取年
  563. string year = date.Substring(0, 4);
  564. //验证合法性
  565. if (Convert.ToInt32(year) < 1900 || Convert.ToInt32(year) > 2100)
  566. {
  567. return false;
  568. }
  569. //拼接日期
  570. date = Convert.ToDateTime(year).ToString("d");
  571. return true;
  572. }
  573. #endregion
  574. return false;
  575. }
  576. }
  577. #endregion
  578. #region 验证身份证是否合法
  579. /// <summary>
  580. /// 验证身份证是否合法
  581. /// </summary>
  582. /// <param name="idCard">要验证的身份证</param>
  583. public static bool IsIdCard(string idCard)
  584. {
  585. //如果为空,认为验证合格
  586. if (IsNullOrEmpty(idCard))
  587. {
  588. return true;
  589. }
  590. //清除要验证字符串中的空格
  591. idCard = idCard.Trim();
  592. //模式字符串
  593. StringBuilder pattern = new StringBuilder();
  594. pattern.Append(@"^(11|12|13|14|15|21|22|23|31|32|33|34|35|36|37|41|42|43|44|45|46|");
  595. pattern.Append(@"50|51|52|53|54|61|62|63|64|65|71|81|82|91)");
  596. pattern.Append(@"(\d{13}|\d{15}[\dx])$");
  597. //验证
  598. return RegexHelper.IsMatch(idCard, pattern.ToString());
  599. }
  600. #endregion
  601. #region 检测客户的输入中是否有危险字符串
  602. /// <summary>
  603. /// 检测客户输入的字符串是否有效,并将原始字符串修改为有效字符串或空字符串。
  604. /// 当检测到客户的输入中有攻击性危险字符串,则返回false,有效返回true。
  605. /// </summary>
  606. /// <param name="input">要检测的字符串</param>
  607. public static bool IsValidInput(ref string input)
  608. {
  609. try
  610. {
  611. if (IsNullOrEmpty(input))
  612. {
  613. //如果是空值,则跳出
  614. return true;
  615. }
  616. else
  617. {
  618. //替换单引号
  619. input = input.Replace("'", "''").Trim();
  620. //检测攻击性危险字符串
  621. string testString = "and |or |exec |insert |select |delete |update |count |chr |mid |master |truncate |char |declare ";
  622. string[] testArray = testString.Split('|');
  623. foreach (string testStr in testArray)
  624. {
  625. if (input.ToLower().IndexOf(testStr) != -1)
  626. {
  627. //检测到攻击字符串,清空传入的值
  628. input = "";
  629. return false;
  630. }
  631. }
  632. //未检测到攻击字符串
  633. return true;
  634. }
  635. }
  636. catch (Exception ex)
  637. {
  638. throw new Exception(ex.Message);
  639. }
  640. }
  641. #endregion
  642. #region 判断对象是否为空
  643. /// <summary>
  644. /// 判断对象是否为空,为空返回true
  645. /// </summary>
  646. /// <typeparam name="T">要验证的对象的类型</typeparam>
  647. /// <param name="data">要验证的对象</param>
  648. public static bool IsNullOrEmpty<T>(T data)
  649. {
  650. //如果为null
  651. if (data == null)
  652. {
  653. return true;
  654. }
  655. //如果为""
  656. if (data.GetType() == typeof(String))
  657. {
  658. if (string.IsNullOrEmpty(data.ToString().Trim()))
  659. {
  660. return true;
  661. }
  662. }
  663. //如果为DBNull
  664. if (data.GetType() == typeof(DBNull))
  665. {
  666. return true;
  667. }
  668. //不为空
  669. return false;
  670. }
  671. /// <summary>
  672. /// 判断对象是否为空,为空返回true
  673. /// </summary>
  674. /// <param name="data">要验证的对象</param>
  675. public static bool IsNullOrEmpty(object data)
  676. {
  677. //如果为null
  678. if (data == null)
  679. {
  680. return true;
  681. }
  682. //如果为""
  683. if (data.GetType() == typeof(String))
  684. {
  685. if (string.IsNullOrEmpty(data.ToString().Trim()))
  686. {
  687. return true;
  688. }
  689. }
  690. //如果为DBNull
  691. if (data.GetType() == typeof(DBNull))
  692. {
  693. return true;
  694. }
  695. //不为空
  696. return false;
  697. }
  698. #endregion
  699. }
  700. }