BaseValidator.cs 13 KB

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