BaseValidator.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  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. }
  183. Control ctrl = Parent;
  184. while(ctrl != null)
  185. {
  186. if(!ctrl.Visible)
  187. {
  188. IsValid = true;
  189. return;
  190. }
  191. ctrl = ctrl.Parent;
  192. }
  193. isPropertiesChecked = false;
  194. if(!PropertiesValid)
  195. {
  196. IsValid = true;
  197. return;
  198. }
  199. IsValid = EvaluateIsValid();
  200. }
  201. protected bool PropertiesValid
  202. {
  203. get
  204. {
  205. if(!isPropertiesChecked)
  206. {
  207. propertiesValid = ControlPropertiesValid();
  208. isPropertiesChecked = true;
  209. }
  210. return propertiesValid;
  211. }
  212. }
  213. protected bool RenderUplevel
  214. {
  215. get
  216. {
  217. return renderUplevel;
  218. }
  219. }
  220. protected override void AddAttributesToRender(HtmlTextWriter writer)
  221. {
  222. bool enabled = base.Enabled;
  223. if (enabled)
  224. Enabled = true;
  225. base.AddAttributesToRender(writer);
  226. if(RenderUplevel)
  227. {
  228. if(ID == null)
  229. {
  230. writer.AddAttribute("id", ClientID);
  231. }
  232. if(ControlToValidate.Length > 0)
  233. {
  234. writer.AddAttribute("controltovalidate", GetControlRenderID(ControlToValidate));
  235. }
  236. if(ErrorMessage.Length > 0)
  237. {
  238. writer.AddAttribute("errormessage", ErrorMessage, true);
  239. }
  240. if(Display == ValidatorDisplay.Static)
  241. {
  242. writer.AddAttribute("display", Enum.Format(typeof(ValidatorDisplay), Display, "G").Replace('_','-'));
  243. //writer.AddAttribute("display", PropertyConverter.EnumToString(typeof(ValidatorDisplay), Display));
  244. }
  245. if(!IsValid)
  246. {
  247. writer.AddAttribute("isvalid", "False");
  248. }
  249. ControlStyle.AddAttributesToRender (writer, this);
  250. if(!enabled)
  251. {
  252. writer.AddAttribute("enabled", "False");
  253. }
  254. }
  255. if(enabled)
  256. {
  257. base.Enabled = false;
  258. }
  259. }
  260. protected void CheckControlValidationProperty(string name, string propertyName)
  261. {
  262. Control ctrl = NamingContainer.FindControl(name);
  263. if(ctrl == null)
  264. {
  265. throw new HttpException(HttpRuntime.FormatResourceString("Validator_control_not_found",
  266. name, propertyName/*, ID*/));
  267. }
  268. PropertyDescriptor pd = GetValidationProperty(ctrl);
  269. if(pd == null)
  270. {
  271. throw new HttpException(HttpRuntime.FormatResourceString("Validator_bad_control_type",
  272. name, propertyName/*, ID*/));
  273. }
  274. }
  275. protected virtual bool ControlPropertiesValid()
  276. {
  277. if(ControlToValidate.Length == 0)
  278. {
  279. throw new HttpException(HttpRuntime.FormatResourceString("Validator_control_blank", ID));
  280. }
  281. CheckControlValidationProperty(ControlToValidate, "ControlToValidate");
  282. return true;
  283. }
  284. protected virtual bool DetermineRenderUplevel()
  285. {
  286. Page page = Page;
  287. if(page == null || page.Request == null)
  288. {
  289. return false;
  290. }
  291. if(EnableClientScript)
  292. {
  293. if(page.Request.Browser.MSDomVersion.Major > 4)
  294. {
  295. return page.Request.Browser.EcmaScriptVersion.CompareTo(new Version(1,2)) >= 0;
  296. }
  297. return false;
  298. }
  299. return false;
  300. }
  301. protected string GetControlRenderID(string name)
  302. {
  303. Control ctrl = FindControl(name);
  304. if(ctrl != null)
  305. {
  306. return ctrl.ClientID;
  307. }
  308. return String.Empty;
  309. }
  310. protected string GetControlValidationValue(string name)
  311. {
  312. Control ctrl = NamingContainer.FindControl(name);
  313. if(ctrl != null)
  314. {
  315. PropertyDescriptor pd = GetValidationProperty(ctrl);
  316. if(pd != null)
  317. {
  318. object item = pd.GetValue (ctrl);
  319. if (item is ListItem)
  320. return ((ListItem) item).Value;
  321. if (item == null)
  322. return String.Empty;
  323. return item.ToString ();
  324. }
  325. }
  326. return null;
  327. }
  328. protected override void OnInit(EventArgs e)
  329. {
  330. base.OnInit(e);
  331. Page.Validators.Add(this);
  332. }
  333. protected override void OnPreRender(EventArgs e)
  334. {
  335. base.OnPreRender(e);
  336. isPreRenderCalled = true;
  337. isPropertiesChecked = false;
  338. renderUplevel = DetermineRenderUplevel();
  339. if(renderUplevel)
  340. {
  341. RegisterValidatorCommonScript();
  342. }
  343. }
  344. protected override void OnUnload(EventArgs e)
  345. {
  346. if(Page != null)
  347. {
  348. Page.Validators.Remove(this);
  349. }
  350. base.OnUnload(e);
  351. }
  352. [MonoTODO("Damn_This_Is_Really_Frustrating___by_Gaurav")]
  353. protected void RegisterValidatorCommonScript()
  354. {
  355. if(Page.IsClientScriptBlockRegistered("ValidatorIncludeScript"))
  356. return;
  357. string jsDirectory = System.Web.UI.Utils.GetScriptLocation(Context);
  358. string jsFile = jsDirectory + "/WebUIValidation.js";
  359. //TODO: Ok, now add the <script language="javascript"> etc
  360. //FIXME: Should I check for 'Explorer'? MS-Net seems to do it!
  361. throw new NotImplementedException();
  362. }
  363. [MonoTODO("I_have_to_know_javascript_for_this_I_know_it_but_for_ALL_browsers_NO")]
  364. protected virtual void RegisterValidatorDeclaration()
  365. {
  366. //FIXME: How to make is more abstract?
  367. //Browser Info... but future browsers???
  368. //I'm confused! This will make it work, at least on IE
  369. string val = "document.all[\"" + ClientID;
  370. val += "\"]";
  371. Page.RegisterArrayDeclaration("Page_Validators", val);
  372. }
  373. [MonoTODO("Render_ing_always_left")]
  374. protected override void Render (HtmlTextWriter writer)
  375. {
  376. bool valid;
  377. if (!Enabled)
  378. return;
  379. if (isPreRenderCalled) {
  380. valid = IsValid;
  381. } else {
  382. isPropertiesChecked = true;
  383. propertiesValid = true;
  384. renderUplevel = false;
  385. valid = true;
  386. }
  387. if (PropertiesValid) {
  388. if (Page != null)
  389. Page.VerifyRenderingInServerForm (this);
  390. ValidatorDisplay dis = Display;
  391. if (RenderUplevel) {
  392. //FIXME: as of now, don't do client-side validation
  393. throw new NotImplementedException();
  394. }
  395. if (!valid && dis != ValidatorDisplay.None) {
  396. RenderBeginTag (writer);
  397. if (Text.Trim ().Length > 0 || HasControls ())
  398. RenderContents (writer);
  399. else
  400. writer.Write (ErrorMessage);
  401. RenderEndTag (writer);
  402. return;
  403. }
  404. } else {
  405. writer.Write ("&nbsp;");
  406. }
  407. }
  408. protected abstract bool EvaluateIsValid();
  409. }
  410. }