StringValueValidator.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. using System;
  2. using System.Globalization;
  3. using System.Text.RegularExpressions;
  4. using Abp.Extensions;
  5. namespace Abp.Runtime.Validation
  6. {
  7. [Serializable]
  8. [Validator("STRING")]
  9. public class StringValueValidator : ValueValidatorBase
  10. {
  11. public bool AllowNull
  12. {
  13. get { return (this["AllowNull"] ?? "false").To<bool>(); }
  14. set { this["AllowNull"] = value.ToString().ToLowerInvariant(); }
  15. }
  16. public int MinLength
  17. {
  18. get { return (this["MinLength"] ?? "0").To<int>(); }
  19. set { this["MinLength"] = value; }
  20. }
  21. public int MaxLength
  22. {
  23. get { return (this["MaxLength"] ?? "0").To<int>(); }
  24. set { this["MaxLength"] = value; }
  25. }
  26. public string RegularExpression
  27. {
  28. get { return this["RegularExpression"] as string; }
  29. set { this["RegularExpression"] = value; }
  30. }
  31. public StringValueValidator()
  32. {
  33. }
  34. public StringValueValidator(int minLength = 0, int maxLength = 0, string regularExpression = null, bool allowNull = false)
  35. {
  36. MinLength = minLength;
  37. MaxLength = maxLength;
  38. RegularExpression = regularExpression;
  39. AllowNull = allowNull;
  40. }
  41. public override bool IsValid(object value)
  42. {
  43. if (value == null)
  44. {
  45. return AllowNull;
  46. }
  47. if (!(value is string))
  48. {
  49. return false;
  50. }
  51. var strValue = value as string;
  52. if (MinLength > 0 && strValue.Length < MinLength)
  53. {
  54. return false;
  55. }
  56. if (MaxLength > 0 && strValue.Length > MaxLength)
  57. {
  58. return false;
  59. }
  60. if (!RegularExpression.IsNullOrEmpty())
  61. {
  62. return Regex.IsMatch(strValue, RegularExpression);
  63. }
  64. return true;
  65. }
  66. }
  67. }