BaseValidator.cs 12 KB

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