BaseValidator.cs 14 KB

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