RegularExpressionValidator.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. if (ctrl == null || ctrl.Trim ().Length == 0)
  67. return true;
  68. bool retVal;
  69. try {
  70. Match match = Regex.Match (ctrl, ValidationExpression);
  71. if (match.Success && match.Index == 0) {
  72. retVal = true;
  73. } else {
  74. retVal = false;
  75. }
  76. } catch (Exception) {
  77. retVal = true;
  78. }
  79. return retVal;
  80. }
  81. }
  82. }