BaseValidator.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  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 ("BaseValidatorEnabled", true); }
  125. set { ViewState ["BaseValidatorEnabled"] = 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. #if NET_2_0
  195. Page.ClientScript.RegisterExpandoAttribute (ClientID, "controltovalidate", GetControlRenderID (ControlToValidate));
  196. #else
  197. writer.AddAttribute ("controltovalidate", GetControlRenderID (ControlToValidate));
  198. #endif
  199. if (ErrorMessage != String.Empty)
  200. #if NET_2_0
  201. Page.ClientScript.RegisterExpandoAttribute (ClientID, "errormessage", ErrorMessage);
  202. #else
  203. writer.AddAttribute ("errormessage", ErrorMessage);
  204. if (Text != String.Empty)
  205. writer.AddAttribute ("text", Text);
  206. #endif
  207. #if NET_2_0
  208. if (ValidationGroup != String.Empty)
  209. Page.ClientScript.RegisterExpandoAttribute (ClientID, "validationGroup", ValidationGroup);
  210. if (SetFocusOnError)
  211. Page.ClientScript.RegisterExpandoAttribute (ClientID, "focusOnError", "t");
  212. #endif
  213. if (!Enabled)
  214. #if NET_2_0
  215. Page.ClientScript.RegisterExpandoAttribute (ClientID, "enabled", "False");
  216. #else
  217. writer.AddAttribute ("enabled", "false", false);
  218. #endif
  219. #if NET_2_0
  220. if (Enabled && !IsValid) {
  221. Page.ClientScript.RegisterExpandoAttribute (ClientID, "isvalid", "False");
  222. #else
  223. if (!IsValid) {
  224. writer.AddAttribute ("isvalid", "false", false);
  225. #endif
  226. }
  227. else {
  228. if (Display == ValidatorDisplay.Static)
  229. writer.AddStyleAttribute ("visibility", "hidden");
  230. else
  231. writer.AddStyleAttribute ("display", "none");
  232. }
  233. if (Display != ValidatorDisplay.Static)
  234. #if NET_2_0
  235. Page.ClientScript.RegisterExpandoAttribute (ClientID, "display", Display.ToString ());
  236. #else
  237. writer.AddAttribute ("display", Display.ToString());
  238. #endif
  239. }
  240. base.AddAttributesToRender (writer);
  241. }
  242. protected void CheckControlValidationProperty (string name, string propertyName)
  243. {
  244. Control control = NamingContainer.FindControl (name);
  245. PropertyDescriptor prop = null;
  246. if (control == null)
  247. throw new HttpException (String.Format ("Unable to find control id '{0}'.", name));
  248. prop = BaseValidator.GetValidationProperty (control);
  249. if (prop == null)
  250. throw new HttpException (String.Format ("Unable to find ValidationProperty attribute '{0}' on control '{1}'", propertyName, name));
  251. }
  252. protected virtual bool ControlPropertiesValid ()
  253. {
  254. if (ControlToValidate.Length == 0) {
  255. throw new HttpException (String.Format ("ControlToValidate property of '{0}' cannot be blank.", ID));
  256. }
  257. CheckControlValidationProperty (ControlToValidate, "");
  258. return true;
  259. }
  260. protected virtual bool DetermineRenderUplevel ()
  261. {
  262. if (!EnableClientScript)
  263. return false;
  264. #if TARGET_J2EE
  265. if (HttpContext.Current == null)
  266. return false;
  267. return (
  268. /* From someplace on the web: "JavaScript 1.2
  269. * and later (also known as ECMAScript) has
  270. * built-in support for regular
  271. * expressions" */
  272. ((Page.Request.Browser.EcmaScriptVersion.Major == 1
  273. && Page.Request.Browser.EcmaScriptVersion.Minor >= 2)
  274. || (Page.Request.Browser.EcmaScriptVersion.Major > 1))
  275. /* document.getElementById, .getAttribute,
  276. * etc, are all DOM level 1. I don't think we
  277. * use anything in level 2.. */
  278. && Page.Request.Browser.W3CDomVersion.Major >= 1);
  279. #else
  280. return UplevelHelper.IsUplevel (
  281. System.Web.Configuration.HttpCapabilitiesBase.GetUserAgentForDetection (HttpContext.Current.Request));
  282. #endif
  283. }
  284. protected abstract bool EvaluateIsValid ();
  285. protected string GetControlRenderID (string name)
  286. {
  287. Control control = NamingContainer.FindControl (name);
  288. if (control == null)
  289. return null;
  290. return control.ClientID;
  291. }
  292. protected string GetControlValidationValue (string name)
  293. {
  294. Control control = NamingContainer.FindControl (name);
  295. if (control == null)
  296. return null;
  297. PropertyDescriptor prop = BaseValidator.GetValidationProperty (control);
  298. if (prop == null)
  299. return null;
  300. object o = prop.GetValue (control);
  301. if (o == null)
  302. return String.Empty;
  303. if (o is ListItem)
  304. return ((ListItem) o).Value;
  305. return o.ToString ();
  306. }
  307. public static PropertyDescriptor GetValidationProperty (object o)
  308. {
  309. PropertyDescriptorCollection props;
  310. System.ComponentModel.AttributeCollection col;
  311. props = TypeDescriptor.GetProperties (o);
  312. col = TypeDescriptor.GetAttributes (o);
  313. foreach (Attribute at in col) {
  314. ValidationPropertyAttribute vpa = at as ValidationPropertyAttribute;
  315. if (vpa != null && vpa.Name != null)
  316. return props[vpa.Name];
  317. }
  318. return null;
  319. }
  320. #if NET_2_0
  321. protected internal
  322. #else
  323. protected
  324. #endif
  325. override void OnInit (EventArgs e)
  326. {
  327. /* according to an msdn article, this is done here */
  328. if (Page != null) {
  329. Page.Validators.Add (this);
  330. #if NET_2_0
  331. Page.GetValidators (ValidationGroup).Add (this);
  332. #endif
  333. }
  334. base.OnInit (e);
  335. }
  336. bool pre_render_called = false;
  337. #if NET_2_0
  338. protected internal
  339. #else
  340. protected
  341. #endif
  342. override void OnPreRender (EventArgs e)
  343. {
  344. base.OnPreRender (e);
  345. pre_render_called = true;
  346. ControlPropertiesValid ();
  347. render_uplevel = DetermineRenderUplevel ();
  348. if (render_uplevel) {
  349. RegisterValidatorCommonScript ();
  350. }
  351. }
  352. #if NET_2_0
  353. protected internal
  354. #else
  355. protected
  356. #endif
  357. override void OnUnload (EventArgs e)
  358. {
  359. /* according to an msdn article, this is done here */
  360. if (Page != null) {
  361. Page.Validators.Remove (this);
  362. #if NET_2_0
  363. if (ValidationGroup != "")
  364. Page.GetValidators (ValidationGroup).Remove (this);
  365. #endif
  366. }
  367. base.OnUnload (e);
  368. }
  369. protected void RegisterValidatorCommonScript ()
  370. {
  371. if (!Page.ClientScript.IsClientScriptIncludeRegistered (typeof (BaseValidator), "Mono-System.Web-ValidationClientScriptBlock"))
  372. {
  373. Page.ClientScript.RegisterClientScriptInclude (typeof (BaseValidator), "Mono-System.Web-ValidationClientScriptBlock",
  374. Page.ClientScript.GetWebResourceUrl (typeof (BaseValidator),
  375. #if NET_2_0
  376. "WebUIValidation_2.0.js"));
  377. string webForm = (Page.IsMultiForm ? Page.theForm : "window");
  378. Page.ClientScript.RegisterClientScriptBlock (typeof (BaseValidator), "Mono-System.Web-ValidationClientScriptBlock.Initialize", "WebFormValidation_Initialize(" + webForm + ");", true);
  379. Page.ClientScript.RegisterOnSubmitStatement ("Mono-System.Web-ValidationOnSubmitStatement", "if (!" + webForm + ".ValidatorOnSubmit()) return false;");
  380. Page.ClientScript.RegisterStartupScript (typeof (BaseValidator), "Mono-System.Web-ValidationStartupScript",
  381. @"
  382. " + webForm + @".Page_ValidationActive = false;
  383. " + webForm + @".ValidatorOnLoad();
  384. " + webForm + @".ValidatorOnSubmit = function () {
  385. if (this.Page_ValidationActive) {
  386. return this.ValidatorCommonOnSubmit();
  387. }
  388. return true;
  389. }
  390. ", true);
  391. #else
  392. "WebUIValidation.js"));
  393. Page.ClientScript.RegisterOnSubmitStatement ("Mono-System.Web-ValidationOnSubmitStatement",
  394. "if (!ValidatorOnSubmit()) return false;");
  395. Page.ClientScript.RegisterStartupScript ("Mono-System.Web-ValidationStartupScript",
  396. "<script language=\"JavaScript\">\n" +
  397. "<!--\n" +
  398. "var Page_ValidationActive = false;\n" +
  399. "ValidatorOnLoad();\n" +
  400. "\n" +
  401. "function ValidatorOnSubmit() {\n" +
  402. " if (Page_ValidationActive) {\n" +
  403. " if (!ValidatorCommonOnSubmit())\n" +
  404. " return Page_ClientValidate ();\n" +
  405. " }\n" +
  406. " return true;\n" +
  407. "}\n" +
  408. "// -->\n" +
  409. "</script>\n");
  410. #endif
  411. }
  412. }
  413. protected virtual void RegisterValidatorDeclaration ()
  414. {
  415. Page.ClientScript.RegisterArrayDeclaration ("Page_Validators",
  416. String.Concat ("document.getElementById ('", ClientID, "')"));
  417. }
  418. #if NET_2_0
  419. protected internal
  420. #else
  421. protected
  422. #endif
  423. override void Render (HtmlTextWriter writer)
  424. {
  425. #if NET_2_0
  426. if (!Enabled && !EnableClientScript)
  427. return;
  428. #endif
  429. if (render_uplevel) {
  430. /* according to an msdn article, this is done here */
  431. RegisterValidatorDeclaration ();
  432. }
  433. bool render_tags = false;
  434. bool render_text = false;
  435. bool render_nbsp = false;
  436. bool v = IsValid;
  437. if (!pre_render_called) {
  438. render_tags = true;
  439. render_text = true;
  440. }
  441. else if (render_uplevel) {
  442. render_tags = true;
  443. #if NET_2_0
  444. render_text = Display != ValidatorDisplay.None;
  445. #else
  446. if (Display != ValidatorDisplay.None)
  447. render_text = !v || Display == ValidatorDisplay.Dynamic;
  448. #endif
  449. }
  450. else {
  451. if (Display != ValidatorDisplay.None) {
  452. render_tags = !v;
  453. render_text = !v;
  454. render_nbsp = v && Display == ValidatorDisplay.Static;
  455. }
  456. }
  457. if (render_tags) {
  458. AddAttributesToRender (writer);
  459. writer.RenderBeginTag (HtmlTextWriterTag.Span);
  460. }
  461. if (render_text || render_nbsp) {
  462. string text;
  463. if (render_text) {
  464. text = Text;
  465. if (text == "")
  466. text = ErrorMessage;
  467. } else {
  468. text = "&nbsp;";
  469. }
  470. writer.Write (text);
  471. }
  472. if (render_tags) {
  473. writer.RenderEndTag ();
  474. }
  475. }
  476. /* the docs say "public sealed" here */
  477. #if NET_2_0
  478. public
  479. #else
  480. public virtual
  481. #endif
  482. void Validate ()
  483. {
  484. if (Enabled && Visible)
  485. IsValid = ControlPropertiesValid () && EvaluateIsValid ();
  486. else
  487. IsValid = true;
  488. }
  489. }
  490. }