RegularExpressionValidator.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /**
  2. * Namespace: System.Web.UI.WebControls
  3. * Class: RegularExpressionValidator
  4. *
  5. * Author: Gaurav Vaish
  6. * Maintainer: [email protected]
  7. * Contact: <[email protected]>, <[email protected]>
  8. * Implementation: yes
  9. * Status: 100%
  10. *
  11. * (C) Gaurav Vaish (2002)
  12. */
  13. using System;
  14. using System.Web;
  15. using System.Web.UI;
  16. using System.Text.RegularExpressions;
  17. namespace System.Web.UI.WebControls
  18. {
  19. public class RegularExpressionValidator : BaseValidator
  20. {
  21. public RegularExpressionValidator(): base()
  22. {
  23. }
  24. public string ValidationExpression
  25. {
  26. get
  27. {
  28. object o = ViewState["ValidationExpression"];
  29. if(o != null)
  30. {
  31. return (string)o;
  32. }
  33. return String.Empty;
  34. }
  35. set
  36. {
  37. try
  38. {
  39. Regex.IsMatch("", value);
  40. } catch(Exception)
  41. {
  42. throw new HttpException(HttpRuntime.FormatString("Validator_bad_regex", value));
  43. }
  44. ViewState["ValidationExpression"] = value;
  45. }
  46. }
  47. protected override void AddAttributesToRender(HtmlTextWriter writer)
  48. {
  49. base.AddAttributesToRender(writer);
  50. if(base.RenderUplevel)
  51. {
  52. writer.AddAttribute("evaluationfunction", "RegularExpressionValidatorEvaluateIsValid");
  53. string exp = ValidationExpression;
  54. if(exp.Length > 0)
  55. {
  56. writer.AddAttribute("validationexpression", exp);
  57. }
  58. }
  59. }
  60. protected override bool EvaluateIsValid()
  61. {
  62. string ctrl = GetControlValidationValue(ControlToValidate);
  63. bool retVal = true;
  64. if(ctrl == null || ctr.Trim.Length == 0)
  65. {
  66. return true;
  67. }
  68. try
  69. {
  70. Match match = Regex.Match(ctrl, ValidationExpression);
  71. if(match.Success && match.Index > 0 && match.Length == ctrl.Length)
  72. {
  73. retVal = true;
  74. } else
  75. {
  76. retVal = false;
  77. }
  78. } catch(Exception)
  79. {
  80. retval = true;
  81. }
  82. return retVal;
  83. }
  84. }
  85. }