IsSN.cs 3.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using System;
  2. using System.Globalization;
  3. using System.Text.RegularExpressions;
  4. using System.Windows.Controls;
  5. namespace CmwtatDigital.Domain
  6. {
  7. class IsSN : ValidationRule
  8. {
  9. #region 匹配方法
  10. /// <summary>
  11. /// 验证字符串是否匹配正则表达式描述的规则
  12. /// </summary>
  13. /// <param name="inputStr">待验证的字符串</param>
  14. /// <param name="patternStr">正则表达式字符串</param>
  15. /// <returns>是否匹配</returns>
  16. public static bool IsMatch(string inputStr, string patternStr)
  17. {
  18. return IsMatch(inputStr, patternStr, false, false);
  19. }
  20. /// <summary>
  21. /// 验证字符串是否匹配正则表达式描述的规则
  22. /// </summary>
  23. /// <param name="inputStr">待验证的字符串</param>
  24. /// <param name="patternStr">正则表达式字符串</param>
  25. /// <param name="ifIgnoreCase">匹配时是否不区分大小写</param>
  26. /// <returns>是否匹配</returns>
  27. public static bool IsMatch(string inputStr, string patternStr, bool ifIgnoreCase)
  28. {
  29. return IsMatch(inputStr, patternStr, ifIgnoreCase, false);
  30. }
  31. /// <summary>
  32. /// 验证字符串是否匹配正则表达式描述的规则
  33. /// </summary>
  34. /// <param name="inputStr">待验证的字符串</param>
  35. /// <param name="patternStr">正则表达式字符串</param>
  36. /// <param name="ifIgnoreCase">匹配时是否不区分大小写</param>
  37. /// <param name="ifValidateWhiteSpace">是否验证空白字符串</param>
  38. /// <returns>是否匹配</returns>
  39. public static bool IsMatch(string inputStr, string patternStr, bool ifIgnoreCase, bool ifValidateWhiteSpace)
  40. {
  41. if (!ifValidateWhiteSpace && string.IsNullOrEmpty(inputStr))
  42. return false;//如果不要求验证空白字符串而此时传入的待验证字符串为空白字符串,则不匹配
  43. Regex regex = null;
  44. if (ifIgnoreCase)
  45. regex = new Regex(patternStr, RegexOptions.IgnoreCase);//指定不区分大小写的匹配
  46. else
  47. regex = new Regex(patternStr);
  48. return regex.IsMatch(inputStr);
  49. }
  50. #endregion
  51. public override ValidationResult Validate(object value, CultureInfo cultureInfo)
  52. {
  53. //Console.WriteLine("\""+value+"\"");
  54. //return string.IsNullOrWhiteSpace((value ?? "").ToString())
  55. // ? new ValidationResult(false, "Key is required.")
  56. // : ValidationResult.ValidResult;
  57. string pattern = @"^[a-zA-Z0-9]{5}-[a-zA-Z0-9]{5}-[a-zA-Z0-9]{5}-[a-zA-Z0-9]{5}-[a-zA-Z0-9]{5}$";
  58. if (IsMatch((value ?? "").ToString(), pattern))
  59. {
  60. return ValidationResult.ValidResult;
  61. }
  62. else if (string.IsNullOrWhiteSpace((value ?? "").ToString()))
  63. {
  64. return new ValidationResult(false, "Please enter the key for the current edition.");
  65. }
  66. else
  67. {
  68. return new ValidationResult(false, "Invalid format.");
  69. }
  70. }
  71. }
  72. }