RegularExpressionValidator.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. [ToolboxData("<{0}:RegularExpressionValidator runat=\"server\" "
  20. + "ErrorMessage=\"RegularExpressionValidator\">"
  21. + "</{0}:RegularExpressionValidator>")]
  22. public class RegularExpressionValidator : BaseValidator
  23. {
  24. public RegularExpressionValidator(): base()
  25. {
  26. }
  27. public string ValidationExpression
  28. {
  29. get
  30. {
  31. object o = ViewState["ValidationExpression"];
  32. if(o != null)
  33. {
  34. return (string)o;
  35. }
  36. return String.Empty;
  37. }
  38. set
  39. {
  40. try
  41. {
  42. Regex.IsMatch("", value);
  43. } catch(Exception)
  44. {
  45. throw new HttpException(HttpRuntime.FormatResourceString("Validator_bad_regex", value));
  46. }
  47. ViewState["ValidationExpression"] = value;
  48. }
  49. }
  50. protected override void AddAttributesToRender(HtmlTextWriter writer)
  51. {
  52. base.AddAttributesToRender(writer);
  53. if(base.RenderUplevel)
  54. {
  55. writer.AddAttribute("evaluationfunction", "RegularExpressionValidatorEvaluateIsValid");
  56. string exp = ValidationExpression;
  57. if(exp.Length > 0)
  58. {
  59. writer.AddAttribute("validationexpression", exp);
  60. }
  61. }
  62. }
  63. protected override bool EvaluateIsValid()
  64. {
  65. string ctrl = GetControlValidationValue(ControlToValidate);
  66. bool retVal = true;
  67. if(ctrl == null || ctrl.Trim().Length == 0)
  68. {
  69. return true;
  70. }
  71. try
  72. {
  73. Match match = Regex.Match(ctrl, ValidationExpression);
  74. if(match.Success && match.Index > 0 && match.Length == ctrl.Length)
  75. {
  76. retVal = true;
  77. } else
  78. {
  79. retVal = false;
  80. }
  81. } catch(Exception)
  82. {
  83. retVal = true;
  84. }
  85. return retVal;
  86. }
  87. }
  88. }