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