2007-08-30 Igor Zelmanovich <igorz@mainsoft.com>
[mono.git] / mcs / class / System.Web / System.Web.UI.WebControls / BaseValidator.cs
1 //
2 // System.Web.UI.WebControls.BaseValidator
3 //
4 // Authors:
5 //      Chris Toshok (toshok@novell.com)
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
29 using System.Web.Configuration;
30 using System.ComponentModel;
31 using System.Drawing;
32 using System.Reflection;
33 using System.Collections;
34 using System.Security.Permissions;
35
36 namespace System.Web.UI.WebControls {
37
38         // CAS
39         [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
40         [AspNetHostingPermission (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
41         // attributes
42         [DefaultProperty("ErrorMessage")]
43         [Designer("System.Web.UI.Design.WebControls.BaseValidatorDesigner, " + Consts.AssemblySystem_Design, "System.ComponentModel.Design.IDesigner")]
44         public abstract class BaseValidator : Label, IValidator
45         {
46                 bool render_uplevel;
47                 bool valid;
48                 Color forecolor;
49
50                 protected BaseValidator ()
51                 {
52                         this.valid = true;
53                         this.ForeColor = Color.Red;
54                 }
55
56                 // New in NET1.1 sp1
57                 [Browsable(false)]
58 #if ONLY_1_1
59                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
60 #endif          
61                 [EditorBrowsable(EditorBrowsableState.Never)]
62                 public override string AssociatedControlID {
63                         get {
64                                 return base.AssociatedControlID;
65                         }
66                         set {
67                                 base.AssociatedControlID = value;
68                         }
69                 }
70
71 #if NET_2_0
72                 [Themeable (false)]
73                 [DefaultValue ("")]
74                 public virtual string ValidationGroup {
75                         get { return ViewState.GetString ("ValidationGroup", String.Empty); }
76                         set { ViewState["ValidationGroup"] = value; }
77                 }
78
79                 [Themeable (false)]
80                 [DefaultValue (false)]
81                 public bool SetFocusOnError {
82                         get { return ViewState.GetBool ("SetFocusOnError", false); }
83                         set { ViewState["SetFocusOnError"] = value; }
84                 }
85
86                 /* listed in corcompare */
87                 [MonoTODO("Why override?")]
88                 [PersistenceMode (PersistenceMode.InnerDefaultProperty)]
89                 [DefaultValue ("")]
90                 public override string Text 
91                 {
92                         get { return base.Text; }
93                         set { base.Text = value; }
94                 }
95 #endif
96
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 { return ViewState.GetString ("ControlToValidate", String.Empty); }
107                         set { ViewState ["ControlToValidate"] = value; }
108                 }
109
110 #if NET_2_0
111                 [Themeable (false)]
112 #endif
113 #if ONLY_1_1            
114                 [Bindable(true)]
115 #endif          
116                 [DefaultValue(ValidatorDisplay.Static)]
117                 [WebSysDescription ("")]
118                 [WebCategory ("Appearance")]
119                 public ValidatorDisplay Display {
120                         get { return (ValidatorDisplay)ViewState.GetInt ("Display", (int)ValidatorDisplay.Static); }
121                         set { ViewState ["Display"] = (int)value; }
122                 }
123
124 #if NET_2_0
125                 [Themeable (false)]
126 #endif
127                 [DefaultValue(true)]
128                 [WebSysDescription ("")]
129                 [WebCategory ("Behavior")]
130                 public bool EnableClientScript {
131                         get { return ViewState.GetBool ("EnableClientScript", true); }
132                         set { ViewState ["EnableClientScript"] = value; }
133                 }
134
135                 public override bool Enabled {
136                         get { return ViewState.GetBool ("BaseValidatorEnabled", true); }
137                         set { ViewState ["BaseValidatorEnabled"] = value; }
138                 }
139
140 #if NET_2_0
141                 [Localizable (true)]
142 #endif
143 #if ONLY_1_1
144                 [Bindable(true)]
145 #endif          
146                 [DefaultValue("")]
147                 [WebSysDescription ("")]
148                 [WebCategory ("Appearance")]
149 #if NET_2_0
150                 public
151 #else
152                 public virtual
153 #endif
154                 string ErrorMessage {
155                         get { return ViewState.GetString ("ErrorMessage", String.Empty); }
156                         set { ViewState ["ErrorMessage"] = value; }
157                 }
158
159                 [DefaultValue(typeof (Color), "Red")]
160                 public override Color ForeColor {
161                         get { return forecolor; }
162                         set {
163                                 forecolor = value;
164                                 base.ForeColor = value;
165                         }
166                 }
167
168                 [Browsable(false)]
169                 [DefaultValue(true)]
170 #if NET_2_0
171                 [Themeable (false)]
172 #endif
173                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
174                 [WebSysDescription ("")]
175                 [WebCategory ("Misc")]
176 #if NET_2_0
177                 public
178 #else
179                 public virtual
180 #endif
181                 bool IsValid {
182                         get { return valid; }
183                         set { valid = value; }
184                 }
185
186                 protected bool PropertiesValid {
187                         get {
188                                 Control control = NamingContainer.FindControl (ControlToValidate);
189                                 if (control == null)
190                                         return false;
191                                 else
192                                         return true;
193                         }
194                 }
195
196                 protected bool RenderUplevel {
197                         get { return render_uplevel; }
198                 }
199
200                 internal bool GetRenderUplevel ()
201                 {
202                         return render_uplevel;
203                 }
204
205                 protected override void AddAttributesToRender (HtmlTextWriter writer)
206                 {
207                         /* if we're rendering uplevel, add our attributes */
208                         if (render_uplevel) {
209                                 /* force an ID here if we weren't assigned one */
210                                 if (ID == null)
211                                         writer.AddAttribute(HtmlTextWriterAttribute.Id, ClientID);
212
213                                 if (ControlToValidate != String.Empty)
214 #if NET_2_0
215                                         Page.ClientScript.RegisterExpandoAttribute (ClientID, "controltovalidate", GetControlRenderID (ControlToValidate));
216 #else
217                                         writer.AddAttribute ("controltovalidate", GetControlRenderID (ControlToValidate));
218 #endif
219
220                                 if (ErrorMessage != String.Empty)
221 #if NET_2_0
222                                         Page.ClientScript.RegisterExpandoAttribute (ClientID, "errormessage", ErrorMessage);
223 #else
224                                         writer.AddAttribute ("errormessage", ErrorMessage);
225
226                                 if (Text != String.Empty)
227                                         writer.AddAttribute ("text", Text);
228 #endif
229
230 #if NET_2_0
231                                 if (ValidationGroup != String.Empty)
232                                         Page.ClientScript.RegisterExpandoAttribute (ClientID, "validationGroup", ValidationGroup);
233
234                                 if (SetFocusOnError)
235                                         Page.ClientScript.RegisterExpandoAttribute (ClientID, "focusOnError", "t");
236 #endif
237                                 if (!Enabled)
238 #if NET_2_0
239                                         Page.ClientScript.RegisterExpandoAttribute (ClientID, "enabled", "False");
240 #else
241                                         writer.AddAttribute ("enabled", "false", false);
242 #endif
243
244 #if NET_2_0
245                                 if (Enabled && !IsValid) {
246                                         Page.ClientScript.RegisterExpandoAttribute (ClientID, "isvalid", "False");
247 #else
248                                 if (!IsValid) {
249                                         writer.AddAttribute ("isvalid", "false", false);
250 #endif
251                                 }
252                                 else {
253                                         if (Display == ValidatorDisplay.Static)
254                                                 writer.AddStyleAttribute ("visibility", "hidden");
255                                         else
256                                                 writer.AddStyleAttribute ("display", "none");
257                                 }
258
259                                 if (Display != ValidatorDisplay.Static)
260 #if NET_2_0
261                                         Page.ClientScript.RegisterExpandoAttribute (ClientID, "display", Display.ToString ());
262 #else
263                                         writer.AddAttribute ("display", Display.ToString());
264 #endif
265                         }
266
267                         base.AddAttributesToRender (writer);
268                 }
269
270                 protected void CheckControlValidationProperty (string name, string propertyName)
271                 {
272                         Control control = NamingContainer.FindControl (name);
273                         PropertyDescriptor prop = null;
274
275                         if (control == null)
276                                 throw new HttpException (String.Format ("Unable to find control id '{0}'.", name));
277
278                         prop = BaseValidator.GetValidationProperty (control);
279                         if (prop == null)
280                                 throw new HttpException (String.Format ("Unable to find ValidationProperty attribute '{0}' on control '{1}'", propertyName, name));
281                 }
282
283                 protected virtual bool ControlPropertiesValid ()
284                 {
285                         if (ControlToValidate.Length == 0) {
286                                 throw new HttpException (String.Format ("ControlToValidate property of '{0}' cannot be blank.", ID));
287                         }
288
289                         CheckControlValidationProperty (ControlToValidate, "");
290
291                         return true;
292                 }
293
294                 protected virtual bool DetermineRenderUplevel ()
295                 {
296                         if (!EnableClientScript)
297                                 return false;
298 #if TARGET_J2EE
299                         if (HttpContext.Current == null)
300                                 return false;
301
302                         return (
303                                 /* From someplace on the web: "JavaScript 1.2
304                                  * and later (also known as ECMAScript) has
305                                  * built-in support for regular
306                                  * expressions" */
307                                 ((Page.Request.Browser.EcmaScriptVersion.Major == 1
308                                   && Page.Request.Browser.EcmaScriptVersion.Minor >= 2)
309                                  || (Page.Request.Browser.EcmaScriptVersion.Major > 1))
310
311                                 /* document.getElementById, .getAttribute,
312                                  * etc, are all DOM level 1.  I don't think we
313                                  * use anything in level 2.. */
314                                 && Page.Request.Browser.W3CDomVersion.Major >= 1);
315 #else
316                         return UplevelHelper.IsUplevel (
317                                 System.Web.Configuration.HttpCapabilitiesBase.GetUserAgentForDetection (HttpContext.Current.Request));
318 #endif
319                 }
320
321                 protected abstract bool EvaluateIsValid ();
322
323                 protected string GetControlRenderID (string name)
324                 {
325                         Control control = NamingContainer.FindControl (name);
326                         if (control == null)
327                                 return null;
328
329                         return control.ClientID;
330                 }
331
332                 protected string GetControlValidationValue (string name)
333                 {
334                         Control control = NamingContainer.FindControl (name);
335
336                         if (control == null)
337                                 return null;
338
339                         PropertyDescriptor prop = BaseValidator.GetValidationProperty (control);
340                         if (prop == null)
341                                 return null;
342
343                         object o = prop.GetValue (control);
344
345                         if (o == null)
346                                 return String.Empty;
347                         
348                         if (o is ListItem)
349                                 return ((ListItem) o).Value;
350                         
351                         return o.ToString ();
352                 }
353
354                 public static PropertyDescriptor GetValidationProperty (object o)
355                 {
356                         PropertyDescriptorCollection props;
357                         System.ComponentModel.AttributeCollection col;
358
359                         props = TypeDescriptor.GetProperties (o);
360                         col = TypeDescriptor.GetAttributes (o);
361
362                         foreach (Attribute at in col) {
363                                 ValidationPropertyAttribute vpa = at as ValidationPropertyAttribute;
364                                 if (vpa != null && vpa.Name != null)
365                                         return props[vpa.Name];
366                         }
367
368                         return null;
369                 }
370
371 #if NET_2_0
372                 protected internal
373 #else           
374                 protected
375 #endif          
376                 override void OnInit (EventArgs e)
377                 {
378                         /* according to an msdn article, this is done here */
379                         if (Page != null) {
380                                 Page.Validators.Add (this);
381
382 #if NET_2_0
383                                 Page.GetValidators (ValidationGroup).Add (this);
384 #endif
385                         }
386                         base.OnInit (e);
387                 }
388
389                 bool pre_render_called = false;
390
391 #if NET_2_0
392                 protected internal
393 #else
394                 protected
395 #endif          
396                 override void OnPreRender (EventArgs e)
397                 {
398                         base.OnPreRender (e);
399
400                         pre_render_called = true;
401                         
402                         ControlPropertiesValid ();
403
404                         render_uplevel = DetermineRenderUplevel ();
405                         if (render_uplevel) {
406                                 RegisterValidatorCommonScript ();
407                         }
408                 }
409
410 #if NET_2_0
411                 protected internal
412 #else           
413                 protected
414 #endif          
415                 override void OnUnload (EventArgs e)
416                 {
417                         /* according to an msdn article, this is done here */
418                         if (Page != null) {
419                                 Page.Validators.Remove (this);
420
421 #if NET_2_0
422                                 if (ValidationGroup != "")
423                                         Page.GetValidators (ValidationGroup).Remove (this);
424 #endif
425
426                         }
427                         base.OnUnload (e);
428                 }
429
430                 protected void RegisterValidatorCommonScript ()
431                 {
432                         if (!Page.ClientScript.IsClientScriptIncludeRegistered (typeof (BaseValidator), "Mono-System.Web-ValidationClientScriptBlock"))
433                         {
434                                 Page.ClientScript.RegisterClientScriptInclude (typeof (BaseValidator), "Mono-System.Web-ValidationClientScriptBlock",
435                                         Page.ClientScript.GetWebResourceUrl (typeof (BaseValidator), 
436 #if NET_2_0
437                                                 "WebUIValidation_2.0.js"));
438                                 string webForm = (Page.IsMultiForm ? Page.theForm : "window");
439                                 Page.ClientScript.RegisterClientScriptBlock (typeof (BaseValidator), "Mono-System.Web-ValidationClientScriptBlock.Initialize", "WebFormValidation_Initialize(" + webForm + ");", true);
440                                 Page.ClientScript.RegisterOnSubmitStatement ("Mono-System.Web-ValidationOnSubmitStatement", "if (!" + webForm + ".ValidatorOnSubmit()) return false;");
441                                 Page.ClientScript.RegisterStartupScript (typeof (BaseValidator), "Mono-System.Web-ValidationStartupScript",
442 @"
443 " + webForm + @".Page_ValidationActive = false;
444 " + webForm + @".ValidatorOnLoad();
445 " + webForm + @".ValidatorOnSubmit = function () {
446         if (this.Page_ValidationActive) {
447                 return this.ValidatorCommonOnSubmit();
448         }
449         return true;
450 }
451 ", true);
452 #else           
453                                                 "WebUIValidation.js"));
454
455                                 Page.ClientScript.RegisterOnSubmitStatement ("Mono-System.Web-ValidationOnSubmitStatement",
456                                                                              "if (!ValidatorOnSubmit()) return false;");
457                                 Page.ClientScript.RegisterStartupScript ("Mono-System.Web-ValidationStartupScript",
458                                                                          "<script language=\"JavaScript\">\n" + 
459                                                                          "<!--\n" + 
460                                                                          "var Page_ValidationActive = false;\n" + 
461                                                                          "ValidatorOnLoad();\n" +
462                                                                          "\n" + 
463                                                                          "function ValidatorOnSubmit() {\n" + 
464                                                                          "        if (Page_ValidationActive) {\n" + 
465                                                                          "                if (!ValidatorCommonOnSubmit())\n" +
466                                                                          "                        return Page_ClientValidate ();\n" +
467                                                                          "        }\n" + 
468                                                                          "        return true;\n" + 
469                                                                          "}\n" + 
470                                                                          "// -->\n" + 
471                                                                          "</script>\n");
472 #endif
473                         }
474                 }
475
476                 protected virtual void RegisterValidatorDeclaration ()
477                 {
478                         Page.ClientScript.RegisterArrayDeclaration ("Page_Validators",
479                                                                     String.Format ("document.getElementById ('{0}')", ClientID));
480                 }
481
482 #if NET_2_0
483                 protected internal
484 #else           
485                 protected
486 #endif          
487                 override void Render (HtmlTextWriter writer)
488                 {
489 #if NET_2_0
490                         if (!Enabled && !EnableClientScript)
491                                 return;
492 #endif
493                         if (render_uplevel) {
494                                 /* according to an msdn article, this is done here */
495                                 RegisterValidatorDeclaration ();
496                         }
497
498                         bool render_tags = false;
499                         bool render_text = false;
500                         bool render_nbsp = false;
501                         bool v = IsValid;
502
503                         if (!pre_render_called) {
504                                 render_tags = true;
505                                 render_text = true;
506                         }
507                         else if (render_uplevel) {
508                                 render_tags = true;
509 #if NET_2_0
510                                 render_text = Display != ValidatorDisplay.None;
511 #else
512                                 if (Display != ValidatorDisplay.None)
513                                         render_text = !v || Display == ValidatorDisplay.Dynamic;
514 #endif
515                         }
516                         else {
517                                 if (Display == ValidatorDisplay.Static) {
518                                         render_tags = !v;
519                                         render_text = !v;
520                                         render_nbsp = v;
521                                 }
522                         }
523
524                         if (render_tags) {
525                                 AddAttributesToRender (writer);
526                                 writer.RenderBeginTag (HtmlTextWriterTag.Span);
527                         }
528
529                         if (render_text || render_nbsp) {
530                                 string text;
531                                 if (render_text) {
532                                         text = Text;
533                                         if (text == "")
534                                                 text = ErrorMessage;
535                                 } else {
536                                         text = "&nbsp;";
537                                 }
538
539                                 writer.Write (text);
540                         }
541
542
543                         if (render_tags) {
544                                 writer.RenderEndTag ();
545                         }
546                 }
547
548                 /* the docs say "public sealed" here */
549 #if NET_2_0
550                 public
551 #else
552                 public virtual
553 #endif
554                 void Validate ()
555                 {
556                         if (Enabled && Visible)
557                                 IsValid = ControlPropertiesValid () && EvaluateIsValid ();
558                         else
559                                 IsValid = true;
560                 }
561         }
562
563 }