BaseValidator.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. //
  2. // System.Web.UI.WebControls.BaseValidator.cs
  3. //
  4. // Authors:
  5. // Gaurav Vaish ([email protected])
  6. // Gonzalo Paniagua Javier ([email protected])
  7. // Andreas Nahr ([email protected])
  8. //
  9. // (c) 2002 Ximian, Inc. (http://www.ximian.com)
  10. // (C) Gaurav Vaish (2002)
  11. // (C) 2003 Andreas Nahr
  12. //
  13. //
  14. // Permission is hereby granted, free of charge, to any person obtaining
  15. // a copy of this software and associated documentation files (the
  16. // "Software"), to deal in the Software without restriction, including
  17. // without limitation the rights to use, copy, modify, merge, publish,
  18. // distribute, sublicense, and/or sell copies of the Software, and to
  19. // permit persons to whom the Software is furnished to do so, subject to
  20. // the following conditions:
  21. //
  22. // The above copyright notice and this permission notice shall be
  23. // included in all copies or substantial portions of the Software.
  24. //
  25. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  26. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  27. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  28. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  29. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  30. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  31. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  32. //
  33. using System;
  34. using System.ComponentModel;
  35. using System.ComponentModel.Design;
  36. using System.Web;
  37. using System.Web.UI;
  38. using System.Drawing;
  39. namespace System.Web.UI.WebControls
  40. {
  41. [DefaultProperty("ErrorMessage")]
  42. [Designer ("System.Web.UI.Design.WebControls.BaseValidatorDesigner, " + Consts.AssemblySystem_Design, typeof (IDesigner))]
  43. public abstract class BaseValidator: Label, IValidator
  44. {
  45. private bool isValid;
  46. private bool isPreRenderCalled;
  47. private bool isPropertiesChecked;
  48. private bool propertiesValid;
  49. private bool renderUplevel;
  50. protected BaseValidator() : base()
  51. {
  52. isValid = true;
  53. ForeColor = Color.Red;
  54. propertiesValid = true;
  55. isPropertiesChecked = false;
  56. renderUplevel = false;
  57. }
  58. [DefaultValue (""), WebCategory ("Behavior")]
  59. [TypeConverter (typeof (ValidatedControlConverter))]
  60. [WebSysDescription ("The ID of the control to validate.")]
  61. public string ControlToValidate
  62. {
  63. get
  64. {
  65. object o = ViewState["ControlToValidate"];
  66. if(o != null)
  67. {
  68. return (string)o;
  69. }
  70. return String.Empty;
  71. }
  72. set
  73. {
  74. ViewState["ControlToValidate"] = value;
  75. }
  76. }
  77. [DefaultValue (typeof (ValidatorDisplay), "Static"), Bindable (true), WebCategory ("Appearance")]
  78. [WebSysDescription ("Determines how the validator is displayed.")]
  79. public ValidatorDisplay Display
  80. {
  81. get
  82. {
  83. object o = ViewState["Display"];
  84. if(o != null)
  85. {
  86. return (ValidatorDisplay)o;
  87. }
  88. return ValidatorDisplay.Static;
  89. }
  90. set
  91. {
  92. if(!Enum.IsDefined(typeof(ValidatorDisplay), value))
  93. {
  94. throw new ArgumentException();
  95. }
  96. ViewState["Display"] = value;
  97. }
  98. }
  99. [DefaultValue (true), WebCategory ("Behavior")]
  100. [WebSysDescription ("Determines if client script is activated on uplevel browsers.")]
  101. public bool EnableClientScript
  102. {
  103. get
  104. {
  105. object o = ViewState["EnableClientScript"];
  106. if(o != null)
  107. {
  108. return (bool)o;
  109. }
  110. return true;
  111. }
  112. set
  113. {
  114. ViewState["EnableClientScript"] = value;
  115. }
  116. }
  117. public override bool Enabled
  118. {
  119. get
  120. {
  121. return base.Enabled;
  122. }
  123. set
  124. {
  125. if (value == false)
  126. isValid = true;
  127. base.Enabled = value;
  128. }
  129. }
  130. [DefaultValue (""), Bindable (true), WebCategory ("Appearance")]
  131. [WebSysDescription ("An error message that is displayed if the control validates to false.")]
  132. public string ErrorMessage
  133. {
  134. get
  135. {
  136. object o = ViewState["ErrorMessage"];
  137. if(o != null)
  138. {
  139. return (string)o;
  140. }
  141. return String.Empty;
  142. }
  143. set
  144. {
  145. ViewState["ErrorMessage"] = value;
  146. }
  147. }
  148. [DefaultValue (null)]
  149. public override Color ForeColor
  150. {
  151. get
  152. {
  153. return base.ForeColor;
  154. }
  155. set
  156. {
  157. base.ForeColor = value;
  158. }
  159. }
  160. [DefaultValue (true), Browsable (false), WebCategory ("Misc")]
  161. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  162. [WebSysDescription ("Indicates if the control validated to false.")]
  163. public bool IsValid
  164. {
  165. get { return isValid; }
  166. set { isValid = value; }
  167. }
  168. public static PropertyDescriptor GetValidationProperty(object component)
  169. {
  170. System.ComponentModel.AttributeCollection coll = TypeDescriptor.GetAttributes (component);
  171. Type type = typeof (ValidationPropertyAttribute);
  172. ValidationPropertyAttribute attrib = (ValidationPropertyAttribute) coll [type];
  173. if (attrib != null && attrib.Name != null)
  174. return (TypeDescriptor.GetProperties (component)) [attrib.Name];
  175. return null;
  176. }
  177. public void Validate()
  178. {
  179. if(!Visible || (Visible && !Enabled))
  180. {
  181. IsValid = true;
  182. return;
  183. }
  184. Control ctrl = Parent;
  185. while(ctrl != null)
  186. {
  187. if(!ctrl.Visible)
  188. {
  189. IsValid = true;
  190. return;
  191. }
  192. ctrl = ctrl.Parent;
  193. }
  194. isPropertiesChecked = false;
  195. if(!PropertiesValid)
  196. {
  197. IsValid = true;
  198. return;
  199. }
  200. IsValid = EvaluateIsValid();
  201. }
  202. protected bool PropertiesValid
  203. {
  204. get
  205. {
  206. if(!isPropertiesChecked)
  207. {
  208. propertiesValid = ControlPropertiesValid();
  209. isPropertiesChecked = true;
  210. }
  211. return propertiesValid;
  212. }
  213. }
  214. protected bool RenderUplevel
  215. {
  216. get
  217. {
  218. return renderUplevel;
  219. }
  220. }
  221. protected override void AddAttributesToRender(HtmlTextWriter writer)
  222. {
  223. bool enabled = base.Enabled;
  224. if (enabled)
  225. Enabled = true;
  226. base.AddAttributesToRender(writer);
  227. if(RenderUplevel)
  228. {
  229. if(ID == null)
  230. {
  231. writer.AddAttribute("id", ClientID);
  232. }
  233. if(ControlToValidate.Length > 0)
  234. {
  235. writer.AddAttribute("controltovalidate", GetControlRenderID(ControlToValidate));
  236. }
  237. if(ErrorMessage.Length > 0)
  238. {
  239. writer.AddAttribute("errormessage", ErrorMessage, true);
  240. }
  241. if(Display == ValidatorDisplay.Static)
  242. {
  243. writer.AddAttribute("display", Enum.Format(typeof(ValidatorDisplay), Display, "G").Replace('_','-'));
  244. //writer.AddAttribute("display", PropertyConverter.EnumToString(typeof(ValidatorDisplay), Display));
  245. }
  246. if(!IsValid)
  247. {
  248. writer.AddAttribute("isvalid", "False");
  249. }
  250. ControlStyle.AddAttributesToRender (writer, this);
  251. if(!enabled)
  252. {
  253. writer.AddAttribute("enabled", "False");
  254. }
  255. }
  256. if(enabled)
  257. {
  258. base.Enabled = false;
  259. }
  260. }
  261. protected void CheckControlValidationProperty(string name, string propertyName)
  262. {
  263. Control ctrl = NamingContainer.FindControl(name);
  264. if(ctrl == null)
  265. {
  266. throw new HttpException(HttpRuntime.FormatResourceString("Validator_control_not_found",
  267. name, propertyName/*, ID*/));
  268. }
  269. PropertyDescriptor pd = GetValidationProperty(ctrl);
  270. if(pd == null)
  271. {
  272. throw new HttpException(HttpRuntime.FormatResourceString("Validator_bad_control_type",
  273. name, propertyName/*, ID*/));
  274. }
  275. }
  276. protected virtual bool ControlPropertiesValid()
  277. {
  278. if(ControlToValidate.Length == 0)
  279. {
  280. throw new HttpException(HttpRuntime.FormatResourceString("Validator_control_blank", ID));
  281. }
  282. CheckControlValidationProperty(ControlToValidate, "ControlToValidate");
  283. return true;
  284. }
  285. protected virtual bool DetermineRenderUplevel()
  286. {
  287. Page page = Page;
  288. if(page == null || page.Request == null)
  289. {
  290. return false;
  291. }
  292. if(EnableClientScript)
  293. {
  294. if(page.Request.Browser.MSDomVersion.Major > 4)
  295. {
  296. return page.Request.Browser.EcmaScriptVersion.CompareTo(new Version(1,2)) >= 0;
  297. }
  298. return false;
  299. }
  300. return false;
  301. }
  302. protected string GetControlRenderID(string name)
  303. {
  304. Control ctrl = FindControl(name);
  305. if(ctrl != null)
  306. {
  307. return ctrl.ClientID;
  308. }
  309. return String.Empty;
  310. }
  311. protected string GetControlValidationValue(string name)
  312. {
  313. Control ctrl = NamingContainer.FindControl(name);
  314. if(ctrl != null)
  315. {
  316. PropertyDescriptor pd = GetValidationProperty(ctrl);
  317. if(pd != null)
  318. {
  319. object item = pd.GetValue (ctrl);
  320. if (item is ListItem)
  321. return ((ListItem) item).Value;
  322. if (item == null)
  323. return String.Empty;
  324. return item.ToString ();
  325. }
  326. }
  327. return null;
  328. }
  329. protected override void OnInit(EventArgs e)
  330. {
  331. base.OnInit(e);
  332. Page.Validators.Add(this);
  333. }
  334. protected override void OnPreRender(EventArgs e)
  335. {
  336. base.OnPreRender(e);
  337. isPreRenderCalled = true;
  338. isPropertiesChecked = false;
  339. renderUplevel = DetermineRenderUplevel();
  340. if(renderUplevel)
  341. {
  342. RegisterValidatorCommonScript();
  343. }
  344. }
  345. protected override void OnUnload(EventArgs e)
  346. {
  347. if(Page != null)
  348. {
  349. Page.Validators.Remove(this);
  350. }
  351. base.OnUnload(e);
  352. }
  353. [MonoTODO("Damn_This_Is_Really_Frustrating___by_Gaurav")]
  354. protected void RegisterValidatorCommonScript()
  355. {
  356. if(Page.IsClientScriptBlockRegistered("ValidatorIncludeScript"))
  357. return;
  358. string jsDirectory = System.Web.UI.Utils.GetScriptLocation(Context);
  359. string jsFile = jsDirectory + "/WebUIValidation.js";
  360. //TODO: Ok, now add the <script language="javascript"> etc
  361. //FIXME: Should I check for 'Explorer'? MS-Net seems to do it!
  362. throw new NotImplementedException();
  363. }
  364. [MonoTODO("I_have_to_know_javascript_for_this_I_know_it_but_for_ALL_browsers_NO")]
  365. protected virtual void RegisterValidatorDeclaration()
  366. {
  367. //FIXME: How to make is more abstract?
  368. //Browser Info... but future browsers???
  369. //I'm confused! This will make it work, at least on IE
  370. string val = "document.all[\"" + ClientID;
  371. val += "\"]";
  372. Page.RegisterArrayDeclaration("Page_Validators", val);
  373. }
  374. [MonoTODO("Render_ing_always_left")]
  375. protected override void Render (HtmlTextWriter writer)
  376. {
  377. bool valid;
  378. if (!Enabled)
  379. return;
  380. if (isPreRenderCalled) {
  381. valid = IsValid;
  382. } else {
  383. isPropertiesChecked = true;
  384. propertiesValid = true;
  385. renderUplevel = false;
  386. valid = true;
  387. }
  388. if (PropertiesValid) {
  389. if (Page != null)
  390. Page.VerifyRenderingInServerForm (this);
  391. ValidatorDisplay dis = Display;
  392. if (RenderUplevel) {
  393. //FIXME: as of now, don't do client-side validation
  394. throw new NotImplementedException();
  395. }
  396. if (!valid && dis != ValidatorDisplay.None) {
  397. RenderBeginTag (writer);
  398. if (Text.Trim ().Length > 0 || HasControls ())
  399. RenderContents (writer);
  400. else
  401. writer.Write (ErrorMessage);
  402. RenderEndTag (writer);
  403. return;
  404. }
  405. } else {
  406. writer.Write ("&nbsp;");
  407. }
  408. }
  409. protected abstract bool EvaluateIsValid();
  410. }
  411. }