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