BaseValidator.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  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 string ValidationGroup {
  69. get {
  70. return ViewState.GetString ("ValidationGroup", String.Empty);
  71. }
  72. set {
  73. ViewState["ValidationGroup"] = value;
  74. }
  75. }
  76. [Themeable (false)]
  77. [DefaultValue (false)]
  78. public bool SetFocusOnError {
  79. get {
  80. return ViewState.GetBool ("SetFocusOnError", false);
  81. }
  82. set {
  83. ViewState["SetFocusOnError"] = value;
  84. }
  85. }
  86. /* listed in corcompare */
  87. [MonoTODO("Why override?")]
  88. [PersistenceMode (PersistenceMode.InnerDefaultProperty)]
  89. [DefaultValue ("")]
  90. public override string Text
  91. {
  92. get {
  93. return base.Text;
  94. }
  95. set {
  96. base.Text = value;
  97. }
  98. }
  99. #endif
  100. #if NET_2_0
  101. [IDReferenceProperty (typeof (Control))]
  102. [Themeable (false)]
  103. #endif
  104. [TypeConverter(typeof(System.Web.UI.WebControls.ValidatedControlConverter))]
  105. [DefaultValue("")]
  106. [WebSysDescription ("")]
  107. [WebCategory ("Behavior")]
  108. public string ControlToValidate {
  109. get {
  110. return ViewState.GetString ("ControlToValidate", String.Empty);
  111. }
  112. set {
  113. ViewState ["ControlToValidate"] = value;
  114. }
  115. }
  116. #if NET_2_0
  117. [Themeable (false)]
  118. #endif
  119. #if ONLY_1_1
  120. [Bindable(true)]
  121. #endif
  122. [DefaultValue(ValidatorDisplay.Static)]
  123. [WebSysDescription ("")]
  124. [WebCategory ("Appearance")]
  125. public ValidatorDisplay Display {
  126. get {
  127. return (ValidatorDisplay)ViewState.GetInt ("Display", (int)ValidatorDisplay.Static);
  128. }
  129. set {
  130. ViewState ["Display"] = (int)value;
  131. }
  132. }
  133. #if NET_2_0
  134. [Themeable (false)]
  135. #endif
  136. [DefaultValue(true)]
  137. [WebSysDescription ("")]
  138. [WebCategory ("Behavior")]
  139. public bool EnableClientScript {
  140. get {
  141. return ViewState.GetBool ("EnableClientScript", true);
  142. }
  143. set {
  144. ViewState ["EnableClientScript"] = value;
  145. }
  146. }
  147. public override bool Enabled {
  148. get {
  149. return ViewState.GetBool ("Enabled", true);
  150. }
  151. set {
  152. ViewState ["Enabled"] = value;
  153. }
  154. }
  155. #if NET_2_0
  156. [Localizable (true)]
  157. #endif
  158. #if ONLY_1_1
  159. [Bindable(true)]
  160. #endif
  161. [DefaultValue("")]
  162. [WebSysDescription ("")]
  163. [WebCategory ("Appearance")]
  164. public virtual string ErrorMessage {
  165. get {
  166. return ViewState.GetString ("ErrorMessage", String.Empty);
  167. }
  168. set {
  169. ViewState ["ErrorMessage"] = value;
  170. }
  171. }
  172. [DefaultValue(typeof (Color), "Red")]
  173. public override Color ForeColor {
  174. get {
  175. return forecolor;
  176. }
  177. set {
  178. forecolor = value;
  179. base.ForeColor = value;
  180. }
  181. }
  182. [Browsable(false)]
  183. [DefaultValue(true)]
  184. #if NET_2_0
  185. [Themeable (false)]
  186. #endif
  187. [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
  188. [WebSysDescription ("")]
  189. [WebCategory ("Misc")]
  190. public virtual bool IsValid {
  191. get {
  192. return valid;
  193. }
  194. set {
  195. valid = value;
  196. }
  197. }
  198. protected bool PropertiesValid {
  199. get {
  200. Control control = NamingContainer.FindControl (ControlToValidate);
  201. if (control == null)
  202. return false;
  203. else
  204. return true;
  205. }
  206. }
  207. protected bool RenderUplevel {
  208. get {
  209. return render_uplevel;
  210. }
  211. }
  212. internal bool GetRenderUplevel ()
  213. {
  214. return render_uplevel;
  215. }
  216. protected override void AddAttributesToRender (HtmlTextWriter writer)
  217. {
  218. /* if we're rendering uplevel, add our attributes */
  219. if (RenderUplevel) {
  220. /* force an ID here if we weren't assigned one */
  221. if (ID == null)
  222. writer.AddAttribute(HtmlTextWriterAttribute.Id, ClientID);
  223. if (ControlToValidate != String.Empty)
  224. writer.AddAttribute ("controltovalidate", ControlToValidate);
  225. if (ErrorMessage != String.Empty)
  226. writer.AddAttribute ("errormessage", ErrorMessage);
  227. if (Text != String.Empty)
  228. writer.AddAttribute ("text", Text);
  229. if (!Enabled)
  230. writer.AddAttribute ("enabled", "false");
  231. if (!IsValid)
  232. writer.AddAttribute ("isvalid", "false");
  233. if (Display == ValidatorDisplay.Static) {
  234. writer.AddStyleAttribute ("visibility", "hidden");
  235. }
  236. else {
  237. writer.AddAttribute ("display", Display.ToString());
  238. writer.AddStyleAttribute ("display", "none");
  239. }
  240. }
  241. base.AddAttributesToRender (writer);
  242. }
  243. protected void CheckControlValidationProperty (string name, string propertyName)
  244. {
  245. Control control = NamingContainer.FindControl (name);
  246. PropertyDescriptor prop = null;
  247. if (control == null)
  248. throw new HttpException (String.Format ("Unable to find control id '{0}'.", name));
  249. prop = BaseValidator.GetValidationProperty (control);
  250. if (prop == null)
  251. throw new HttpException (String.Format ("Unable to find ValidationProperty attribute '{0}' on control '{1}'", propertyName, name));
  252. }
  253. protected virtual bool ControlPropertiesValid ()
  254. {
  255. if (ControlToValidate.Length == 0) {
  256. throw new HttpException("ControlToValidate property cannot be emtpy");
  257. }
  258. CheckControlValidationProperty (ControlToValidate, "");
  259. return true;
  260. }
  261. protected virtual bool DetermineRenderUplevel ()
  262. {
  263. if (!EnableClientScript)
  264. return false;
  265. try {
  266. if (Page == null || Page.Request == null)
  267. return false;
  268. }
  269. catch {
  270. /* this can happen with a fake Page in nunit
  271. * tests, since Page.Context == null */
  272. return false;
  273. }
  274. return (
  275. /* From someplace on the web: "JavaScript 1.2
  276. * and later (also known as ECMAScript) has
  277. * built-in support for regular
  278. * expressions" */
  279. ((Page.Request.Browser.EcmaScriptVersion.Major == 1
  280. && Page.Request.Browser.EcmaScriptVersion.Minor >= 2)
  281. || (Page.Request.Browser.EcmaScriptVersion.Major > 1))
  282. /* document.getElementById, .getAttribute,
  283. * etc, are all DOM level 1. I don't think we
  284. * use anything in level 2.. */
  285. && Page.Request.Browser.W3CDomVersion.Major >= 1);
  286. }
  287. protected abstract bool EvaluateIsValid ();
  288. protected string GetControlRenderID (string name)
  289. {
  290. Control control = NamingContainer.FindControl (name);
  291. if (control == null)
  292. return null;
  293. return control.ClientID;
  294. }
  295. protected string GetControlValidationValue (string name)
  296. {
  297. Control control = NamingContainer.FindControl (name);
  298. if (control == null)
  299. return null;
  300. PropertyDescriptor prop = BaseValidator.GetValidationProperty (control);
  301. if (prop == null)
  302. return null;
  303. object o = prop.GetValue (control);
  304. if (o is string)
  305. return (string)o;
  306. else if (o is ListItem)
  307. return ((ListItem)o).Value;
  308. else {
  309. // XXX
  310. return null;
  311. }
  312. }
  313. public static PropertyDescriptor GetValidationProperty (object o)
  314. {
  315. PropertyDescriptorCollection props;
  316. System.ComponentModel.AttributeCollection col;
  317. props = TypeDescriptor.GetProperties (o);
  318. col = TypeDescriptor.GetAttributes (o);
  319. foreach (Attribute at in col) {
  320. ValidationPropertyAttribute vpa = at as ValidationPropertyAttribute;
  321. if (vpa != null && vpa.Name != null)
  322. return props[vpa.Name];
  323. }
  324. return null;
  325. }
  326. #if NET_2_0
  327. protected internal
  328. #else
  329. protected
  330. #endif
  331. override void OnInit (EventArgs e)
  332. {
  333. /* according to an msdn article, this is done here */
  334. if (Page != null) {
  335. Page.Validators.Add (this);
  336. #if NET_2_0
  337. if (ValidationGroup != "")
  338. Page.GetValidators (ValidationGroup).Add (this);
  339. #endif
  340. }
  341. base.OnInit (e);
  342. }
  343. bool pre_render_called = false;
  344. #if NET_2_0
  345. protected internal
  346. #else
  347. protected
  348. #endif
  349. override void OnPreRender (EventArgs e)
  350. {
  351. base.OnPreRender (e);
  352. pre_render_called = true;
  353. render_uplevel = DetermineRenderUplevel ();
  354. if (RenderUplevel) {
  355. RegisterValidatorCommonScript ();
  356. Page.ClientScript.RegisterOnSubmitStatement ("Mono-System.Web-ValidationOnSubmitStatement",
  357. "if (!ValidatorOnSubmit()) return false;");
  358. Page.ClientScript.RegisterStartupScript ("Mono-System.Web-ValidationStartupScript",
  359. "<script language=\"JavaScript\">\n" +
  360. "<!--\n" +
  361. "var Page_ValidationActive = false;\n" +
  362. "ValidatorOnLoad();\n" +
  363. "\n" +
  364. "function ValidatorOnSubmit() {\n" +
  365. " if (Page_ValidationActive) {\n" +
  366. " return ValidatorCommonOnSubmit();\n" +
  367. " }\n" +
  368. " return true;\n" +
  369. "}\n" +
  370. "// -->\n" +
  371. "</script>\n");
  372. }
  373. }
  374. #if NET_2_0
  375. protected internal
  376. #else
  377. protected
  378. #endif
  379. override void OnUnload (EventArgs e)
  380. {
  381. /* according to an msdn article, this is done here */
  382. if (Page != null) {
  383. Page.Validators.Remove (this);
  384. #if NET_2_0
  385. if (ValidationGroup != "")
  386. Page.GetValidators (ValidationGroup).Remove (this);
  387. #endif
  388. }
  389. base.OnUnload (e);
  390. }
  391. protected void RegisterValidatorCommonScript ()
  392. {
  393. if (!Page.ClientScript.IsClientScriptBlockRegistered ("Mono-System.Web-ValidationClientScriptBlock")) {
  394. Page.ClientScript.RegisterClientScriptBlock ("Mono-System.Web-ValidationClientScriptBlock",
  395. String.Format ("<script language=\"JavaScript\" src=\"{0}\"></script>",
  396. Page.ClientScript.GetWebResourceUrl (GetType(),
  397. "WebUIValidation.js")));
  398. }
  399. }
  400. protected virtual void RegisterValidatorDeclaration ()
  401. {
  402. Page.ClientScript.RegisterArrayDeclaration ("Page_Validators",
  403. String.Format ("document.getElementById ('{0}')", ClientID));
  404. }
  405. #if NET_2_0
  406. protected internal
  407. #else
  408. protected
  409. #endif
  410. override void Render (HtmlTextWriter writer)
  411. {
  412. if (RenderUplevel) {
  413. /* according to an msdn article, this is done here */
  414. RegisterValidatorDeclaration ();
  415. }
  416. bool render_tags = false;
  417. bool render_text = false;
  418. bool render_nbsp = false;
  419. if (!pre_render_called) {
  420. render_tags = true;
  421. render_text = true;
  422. }
  423. else if (RenderUplevel) {
  424. render_tags = true;
  425. if (Display == ValidatorDisplay.Dynamic)
  426. render_text = true;
  427. }
  428. else {
  429. if (Display == ValidatorDisplay.Static) {
  430. render_tags = !valid;
  431. render_text = !valid;
  432. render_nbsp = valid;
  433. }
  434. }
  435. if (render_tags) {
  436. AddAttributesToRender (writer);
  437. writer.RenderBeginTag (HtmlTextWriterTag.Span);
  438. }
  439. if (render_text || render_nbsp) {
  440. string text;
  441. if (render_text) {
  442. if (Text != "")
  443. text = Text;
  444. else
  445. text = ErrorMessage;
  446. }
  447. else {
  448. text = "&nbsp;";
  449. }
  450. writer.Write (text);
  451. }
  452. if (render_tags) {
  453. writer.RenderEndTag ();
  454. }
  455. }
  456. /* the docs say "public sealed" here */
  457. public virtual void Validate ()
  458. {
  459. if (Enabled && Visible)
  460. valid = ControlPropertiesValid () && EvaluateIsValid ();
  461. else
  462. valid = true;
  463. }
  464. }
  465. }