BaseValidator.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  1. //
  2. // System.Web.UI.WebControls.BaseValidator
  3. //
  4. // Authors:
  5. // Chris Toshok ([email protected])
  6. //
  7. // (C) 2005 Novell, Inc (http://www.novell.com)
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining
  10. // a copy of this software and associated documentation files (the
  11. // "Software"), to deal in the Software without restriction, including
  12. // without limitation the rights to use, copy, modify, merge, publish,
  13. // distribute, sublicense, and/or sell copies of the Software, and to
  14. // permit persons to whom the Software is furnished to do so, subject to
  15. // the following conditions:
  16. //
  17. // The above copyright notice and this permission notice shall be
  18. // included in all copies or substantial portions of the Software.
  19. //
  20. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  21. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  22. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  23. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  24. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  25. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  26. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  27. //
  28. using System.Web.Configuration;
  29. using System.ComponentModel;
  30. using System.Drawing;
  31. using System.Reflection;
  32. using System.Collections;
  33. using System.Security.Permissions;
  34. namespace System.Web.UI.WebControls {
  35. // CAS
  36. [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
  37. [AspNetHostingPermission (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
  38. // attributes
  39. [DefaultProperty("ErrorMessage")]
  40. [Designer("System.Web.UI.Design.WebControls.BaseValidatorDesigner, " + Consts.AssemblySystem_Design, "System.ComponentModel.Design.IDesigner")]
  41. public abstract class BaseValidator : Label, IValidator
  42. {
  43. bool render_uplevel;
  44. bool valid;
  45. Color forecolor;
  46. protected BaseValidator ()
  47. {
  48. this.valid = true;
  49. this.ForeColor = Color.Red;
  50. }
  51. // New in NET1.1 sp1
  52. [Browsable(false)]
  53. #if ONLY_1_1
  54. [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
  55. #endif
  56. [EditorBrowsable(EditorBrowsableState.Never)]
  57. public override string AssociatedControlID {
  58. get {
  59. return base.AssociatedControlID;
  60. }
  61. set {
  62. base.AssociatedControlID = value;
  63. }
  64. }
  65. #if NET_2_0
  66. [Themeable (false)]
  67. [DefaultValue ("")]
  68. public virtual string ValidationGroup {
  69. get { return ViewState.GetString ("ValidationGroup", String.Empty); }
  70. set { ViewState["ValidationGroup"] = value; }
  71. }
  72. [Themeable (false)]
  73. [DefaultValue (false)]
  74. public bool SetFocusOnError {
  75. get { return ViewState.GetBool ("SetFocusOnError", false); }
  76. set { ViewState["SetFocusOnError"] = value; }
  77. }
  78. /* listed in corcompare */
  79. [MonoTODO("Why override?")]
  80. [PersistenceMode (PersistenceMode.InnerDefaultProperty)]
  81. [DefaultValue ("")]
  82. public override string Text
  83. {
  84. get { return base.Text; }
  85. set { base.Text = value; }
  86. }
  87. #endif
  88. #if NET_2_0
  89. [IDReferenceProperty (typeof (Control))]
  90. [Themeable (false)]
  91. #endif
  92. [TypeConverter(typeof(System.Web.UI.WebControls.ValidatedControlConverter))]
  93. [DefaultValue("")]
  94. [WebSysDescription ("")]
  95. [WebCategory ("Behavior")]
  96. public string ControlToValidate {
  97. get { return ViewState.GetString ("ControlToValidate", String.Empty); }
  98. set { ViewState ["ControlToValidate"] = value; }
  99. }
  100. #if NET_2_0
  101. [Themeable (false)]
  102. #endif
  103. #if ONLY_1_1
  104. [Bindable(true)]
  105. #endif
  106. [DefaultValue(ValidatorDisplay.Static)]
  107. [WebSysDescription ("")]
  108. [WebCategory ("Appearance")]
  109. public ValidatorDisplay Display {
  110. get { return (ValidatorDisplay)ViewState.GetInt ("Display", (int)ValidatorDisplay.Static); }
  111. set { ViewState ["Display"] = (int)value; }
  112. }
  113. #if NET_2_0
  114. [Themeable (false)]
  115. #endif
  116. [DefaultValue(true)]
  117. [WebSysDescription ("")]
  118. [WebCategory ("Behavior")]
  119. public bool EnableClientScript {
  120. get { return ViewState.GetBool ("EnableClientScript", true); }
  121. set { ViewState ["EnableClientScript"] = value; }
  122. }
  123. public override bool Enabled {
  124. get { return ViewState.GetBool ("Enabled", true); }
  125. set { ViewState ["Enabled"] = value; }
  126. }
  127. #if NET_2_0
  128. [Localizable (true)]
  129. #endif
  130. #if ONLY_1_1
  131. [Bindable(true)]
  132. #endif
  133. [DefaultValue("")]
  134. [WebSysDescription ("")]
  135. [WebCategory ("Appearance")]
  136. #if NET_2_0
  137. public
  138. #else
  139. public virtual
  140. #endif
  141. string ErrorMessage {
  142. get { return ViewState.GetString ("ErrorMessage", String.Empty); }
  143. set { ViewState ["ErrorMessage"] = value; }
  144. }
  145. [DefaultValue(typeof (Color), "Red")]
  146. public override Color ForeColor {
  147. get { return forecolor; }
  148. set {
  149. forecolor = value;
  150. base.ForeColor = value;
  151. }
  152. }
  153. [Browsable(false)]
  154. [DefaultValue(true)]
  155. #if NET_2_0
  156. [Themeable (false)]
  157. #endif
  158. [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
  159. [WebSysDescription ("")]
  160. [WebCategory ("Misc")]
  161. #if NET_2_0
  162. public
  163. #else
  164. public virtual
  165. #endif
  166. bool IsValid {
  167. get { return valid; }
  168. set { valid = value; }
  169. }
  170. protected bool PropertiesValid {
  171. get {
  172. Control control = NamingContainer.FindControl (ControlToValidate);
  173. if (control == null)
  174. return false;
  175. else
  176. return true;
  177. }
  178. }
  179. protected bool RenderUplevel {
  180. get { return render_uplevel; }
  181. }
  182. internal bool GetRenderUplevel ()
  183. {
  184. return render_uplevel;
  185. }
  186. protected override void AddAttributesToRender (HtmlTextWriter writer)
  187. {
  188. /* if we're rendering uplevel, add our attributes */
  189. if (render_uplevel) {
  190. /* force an ID here if we weren't assigned one */
  191. if (ID == null)
  192. writer.AddAttribute(HtmlTextWriterAttribute.Id, ClientID);
  193. if (ControlToValidate != String.Empty)
  194. writer.AddAttribute ("controltovalidate", GetControlRenderID (ControlToValidate));
  195. if (ErrorMessage != String.Empty)
  196. writer.AddAttribute ("errormessage", ErrorMessage);
  197. if (Text != String.Empty)
  198. writer.AddAttribute ("text", Text);
  199. if (!Enabled)
  200. writer.AddAttribute ("enabled", "false");
  201. if (!IsValid) {
  202. writer.AddAttribute ("isvalid", "false");
  203. }
  204. else {
  205. if (Display == ValidatorDisplay.Static)
  206. writer.AddStyleAttribute ("visibility", "hidden");
  207. else
  208. writer.AddStyleAttribute ("display", "none");
  209. }
  210. if (Display != ValidatorDisplay.Static)
  211. writer.AddAttribute ("display", Display.ToString());
  212. }
  213. base.AddAttributesToRender (writer);
  214. }
  215. protected void CheckControlValidationProperty (string name, string propertyName)
  216. {
  217. Control control = NamingContainer.FindControl (name);
  218. PropertyDescriptor prop = null;
  219. if (control == null)
  220. throw new HttpException (String.Format ("Unable to find control id '{0}'.", name));
  221. prop = BaseValidator.GetValidationProperty (control);
  222. if (prop == null)
  223. throw new HttpException (String.Format ("Unable to find ValidationProperty attribute '{0}' on control '{1}'", propertyName, name));
  224. }
  225. protected virtual bool ControlPropertiesValid ()
  226. {
  227. if (ControlToValidate.Length == 0) {
  228. throw new HttpException("ControlToValidate property cannot be emtpy");
  229. }
  230. CheckControlValidationProperty (ControlToValidate, "");
  231. return true;
  232. }
  233. protected virtual bool DetermineRenderUplevel ()
  234. {
  235. if (!EnableClientScript)
  236. return false;
  237. try {
  238. if (Page == null || Page.Request == null)
  239. return false;
  240. }
  241. catch {
  242. /* this can happen with a fake Page in nunit
  243. * tests, since Page.Context == null */
  244. return false;
  245. }
  246. return (
  247. /* From someplace on the web: "JavaScript 1.2
  248. * and later (also known as ECMAScript) has
  249. * built-in support for regular
  250. * expressions" */
  251. ((Page.Request.Browser.EcmaScriptVersion.Major == 1
  252. && Page.Request.Browser.EcmaScriptVersion.Minor >= 2)
  253. || (Page.Request.Browser.EcmaScriptVersion.Major > 1))
  254. /* document.getElementById, .getAttribute,
  255. * etc, are all DOM level 1. I don't think we
  256. * use anything in level 2.. */
  257. && Page.Request.Browser.W3CDomVersion.Major >= 1);
  258. }
  259. protected abstract bool EvaluateIsValid ();
  260. protected string GetControlRenderID (string name)
  261. {
  262. Control control = NamingContainer.FindControl (name);
  263. if (control == null)
  264. return null;
  265. return control.ClientID;
  266. }
  267. protected string GetControlValidationValue (string name)
  268. {
  269. Control control = NamingContainer.FindControl (name);
  270. if (control == null)
  271. return null;
  272. PropertyDescriptor prop = BaseValidator.GetValidationProperty (control);
  273. if (prop == null)
  274. return null;
  275. object o = prop.GetValue (control);
  276. if (o is string)
  277. return (string)o;
  278. else if (o is ListItem)
  279. return ((ListItem)o).Value;
  280. else {
  281. // XXX
  282. return null;
  283. }
  284. }
  285. public static PropertyDescriptor GetValidationProperty (object o)
  286. {
  287. PropertyDescriptorCollection props;
  288. System.ComponentModel.AttributeCollection col;
  289. props = TypeDescriptor.GetProperties (o);
  290. col = TypeDescriptor.GetAttributes (o);
  291. foreach (Attribute at in col) {
  292. ValidationPropertyAttribute vpa = at as ValidationPropertyAttribute;
  293. if (vpa != null && vpa.Name != null)
  294. return props[vpa.Name];
  295. }
  296. return null;
  297. }
  298. #if NET_2_0
  299. protected internal
  300. #else
  301. protected
  302. #endif
  303. override void OnInit (EventArgs e)
  304. {
  305. /* according to an msdn article, this is done here */
  306. if (Page != null) {
  307. Page.Validators.Add (this);
  308. #if NET_2_0
  309. if (ValidationGroup != "")
  310. Page.GetValidators (ValidationGroup).Add (this);
  311. #endif
  312. }
  313. base.OnInit (e);
  314. }
  315. bool pre_render_called = false;
  316. #if NET_2_0
  317. protected internal
  318. #else
  319. protected
  320. #endif
  321. override void OnPreRender (EventArgs e)
  322. {
  323. base.OnPreRender (e);
  324. pre_render_called = true;
  325. render_uplevel = DetermineRenderUplevel ();
  326. if (render_uplevel) {
  327. RegisterValidatorCommonScript ();
  328. Page.ClientScript.RegisterOnSubmitStatement ("Mono-System.Web-ValidationOnSubmitStatement",
  329. "if (!ValidatorOnSubmit()) return false;");
  330. Page.ClientScript.RegisterStartupScript ("Mono-System.Web-ValidationStartupScript",
  331. "<script language=\"JavaScript\">\n" +
  332. "<!--\n" +
  333. "var Page_ValidationActive = false;\n" +
  334. "ValidatorOnLoad();\n" +
  335. "\n" +
  336. "function ValidatorOnSubmit() {\n" +
  337. " if (Page_ValidationActive) {\n" +
  338. " return ValidatorCommonOnSubmit();\n" +
  339. " }\n" +
  340. " return true;\n" +
  341. "}\n" +
  342. "// -->\n" +
  343. "</script>\n");
  344. }
  345. }
  346. #if NET_2_0
  347. protected internal
  348. #else
  349. protected
  350. #endif
  351. override void OnUnload (EventArgs e)
  352. {
  353. /* according to an msdn article, this is done here */
  354. if (Page != null) {
  355. Page.Validators.Remove (this);
  356. #if NET_2_0
  357. if (ValidationGroup != "")
  358. Page.GetValidators (ValidationGroup).Remove (this);
  359. #endif
  360. }
  361. base.OnUnload (e);
  362. }
  363. protected void RegisterValidatorCommonScript ()
  364. {
  365. if (!Page.ClientScript.IsClientScriptBlockRegistered ("Mono-System.Web-ValidationClientScriptBlock")) {
  366. Page.ClientScript.RegisterClientScriptBlock ("Mono-System.Web-ValidationClientScriptBlock",
  367. String.Format ("<script language=\"JavaScript\" src=\"{0}\"></script>",
  368. Page.ClientScript.GetWebResourceUrl (GetType(),
  369. "WebUIValidation.js")));
  370. }
  371. }
  372. protected virtual void RegisterValidatorDeclaration ()
  373. {
  374. Page.ClientScript.RegisterArrayDeclaration ("Page_Validators",
  375. String.Format ("document.getElementById ('{0}')", ClientID));
  376. }
  377. #if NET_2_0
  378. protected internal
  379. #else
  380. protected
  381. #endif
  382. override void Render (HtmlTextWriter writer)
  383. {
  384. if (render_uplevel) {
  385. /* according to an msdn article, this is done here */
  386. RegisterValidatorDeclaration ();
  387. }
  388. bool render_tags = false;
  389. bool render_text = false;
  390. bool render_nbsp = false;
  391. bool v = IsValid;
  392. if (!pre_render_called) {
  393. render_tags = true;
  394. render_text = true;
  395. }
  396. else if (render_uplevel) {
  397. render_tags = true;
  398. if (Display != ValidatorDisplay.None)
  399. render_text = !v || Display == ValidatorDisplay.Dynamic;
  400. }
  401. else {
  402. if (Display == ValidatorDisplay.Static) {
  403. render_tags = !v;
  404. render_text = !v;
  405. render_nbsp = v;
  406. }
  407. }
  408. if (render_tags) {
  409. AddAttributesToRender (writer);
  410. writer.RenderBeginTag (HtmlTextWriterTag.Span);
  411. }
  412. if (render_text || render_nbsp) {
  413. string text;
  414. if (render_text) {
  415. text = Text;
  416. if (text == "")
  417. text = ErrorMessage;
  418. } else {
  419. text = "&nbsp;";
  420. }
  421. writer.Write (text);
  422. }
  423. if (render_tags) {
  424. writer.RenderEndTag ();
  425. }
  426. }
  427. /* the docs say "public sealed" here */
  428. #if NET_2_0
  429. public
  430. #else
  431. public virtual
  432. #endif
  433. void Validate ()
  434. {
  435. if (Enabled && Visible)
  436. IsValid = ControlPropertiesValid () && EvaluateIsValid ();
  437. else
  438. IsValid = true;
  439. }
  440. }
  441. }