Merge pull request #1218 from AndreyAkinshin/master
[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-2010 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                 bool pre_render_called = false;
50
51                 protected BaseValidator ()
52                 {
53                         this.valid = true;
54                         this.ForeColor = Color.Red;
55                 }
56
57                 // New in NET1.1 sp1
58                 [Browsable(false)]
59                 [EditorBrowsable(EditorBrowsableState.Never)]
60                 public override string AssociatedControlID {
61                         get { return base.AssociatedControlID; }
62                         set { base.AssociatedControlID = value; }
63                 }
64
65                 [Themeable (false)]
66                 [DefaultValue ("")]
67                 public virtual string ValidationGroup {
68                         get { return ViewState.GetString ("ValidationGroup", String.Empty); }
69                         set { ViewState["ValidationGroup"] = value; }
70                 }
71
72                 [Themeable (false)]
73                 [DefaultValue (false)]
74                 public bool SetFocusOnError {
75                         get { return ViewState.GetBool ("SetFocusOnError", false); }
76                         set { ViewState["SetFocusOnError"] = value; }
77                 }
78
79                 /* listed in corcompare */
80                 [MonoTODO("Why override?")]
81                 [PersistenceMode (PersistenceMode.InnerDefaultProperty)]
82                 [DefaultValue ("")]
83                 public override string Text 
84                 {
85                         get { return base.Text; }
86                         set { base.Text = value; }
87                 }
88
89                 [IDReferenceProperty (typeof (Control))]
90                 [Themeable (false)]
91                 [TypeConverter(typeof(System.Web.UI.WebControls.ValidatedControlConverter))]
92                 [DefaultValue("")]
93                 [WebSysDescription ("")]
94                 [WebCategory ("Behavior")]
95                 public string ControlToValidate {
96                         get { return ViewState.GetString ("ControlToValidate", String.Empty); }
97                         set { ViewState ["ControlToValidate"] = value; }
98                 }
99
100                 [Themeable (false)]
101                 [DefaultValue(ValidatorDisplay.Static)]
102                 [WebSysDescription ("")]
103                 [WebCategory ("Appearance")]
104                 public ValidatorDisplay Display {
105                         get { return (ValidatorDisplay)ViewState.GetInt ("Display", (int)ValidatorDisplay.Static); }
106                         set { ViewState ["Display"] = (int)value; }
107                 }
108
109                 [Themeable (false)]
110                 [DefaultValue(true)]
111                 [WebSysDescription ("")]
112                 [WebCategory ("Behavior")]
113                 public bool EnableClientScript {
114                         get { return ViewState.GetBool ("EnableClientScript", true); }
115                         set { ViewState ["EnableClientScript"] = value; }
116                 }
117
118                 public override bool Enabled {
119                         get { return ViewState.GetBool ("BaseValidatorEnabled", true); }
120                         set { ViewState ["BaseValidatorEnabled"] = value; }
121                 }
122
123                 [Localizable (true)]
124                 [DefaultValue("")]
125                 [WebSysDescription ("")]
126                 [WebCategory ("Appearance")]
127                 public string ErrorMessage {
128                         get { return ViewState.GetString ("ErrorMessage", String.Empty); }
129                         set { ViewState ["ErrorMessage"] = value; }
130                 }
131
132                 [DefaultValue(typeof (Color), "Red")]
133                 public override Color ForeColor {
134                         get { return forecolor; }
135                         set {
136                                 forecolor = value;
137                                 base.ForeColor = value;
138                         }
139                 }
140
141                 [Browsable(false)]
142                 [DefaultValue(true)]
143                 [Themeable (false)]
144                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
145                 [WebSysDescription ("")]
146                 [WebCategory ("Misc")]
147                 public bool IsValid {
148                         get { return valid; }
149                         set { valid = value; }
150                 }
151
152                 protected bool PropertiesValid {
153                         get {
154                                 Control control = NamingContainer.FindControl (ControlToValidate);
155                                 if (control == null)
156                                         return false;
157                                 else
158                                         return true;
159                         }
160                 }
161
162                 protected bool RenderUplevel {
163                         get { return render_uplevel; }
164                 }
165
166                 internal bool GetRenderUplevel ()
167                 {
168                         return render_uplevel;
169                 }
170
171                 protected override void AddAttributesToRender (HtmlTextWriter writer)
172                 {
173                         /* if we're rendering uplevel, add our attributes */
174                         if (render_uplevel) {
175                                 /* force an ID here if we weren't assigned one */
176                                 if (ID == null)
177                                         writer.AddAttribute(HtmlTextWriterAttribute.Id, ClientID);
178
179                                 if (ControlToValidate != String.Empty)
180                                         RegisterExpandoAttribute (ClientID, "controltovalidate", GetControlRenderID (ControlToValidate));
181
182                                 if (ErrorMessage != String.Empty)
183                                         RegisterExpandoAttribute (ClientID, "errormessage", ErrorMessage, true);
184
185                                 if (ValidationGroup != String.Empty)
186                                         RegisterExpandoAttribute (ClientID, "validationGroup", ValidationGroup, true);
187
188                                 if (SetFocusOnError)
189                                         RegisterExpandoAttribute (ClientID, "focusOnError", "t");
190
191                                 bool enabled = IsEnabled;
192                                 if (!enabled)
193                                         RegisterExpandoAttribute (ClientID, "enabled", "False");
194
195                                 if (enabled && !IsValid)
196                                         RegisterExpandoAttribute (ClientID, "isvalid", "False");
197                                 else {
198                                         if (Display == ValidatorDisplay.Static)
199                                                 writer.AddStyleAttribute ("visibility", "hidden");
200                                         else
201                                                 writer.AddStyleAttribute ("display", "none");
202                                 }
203
204                                 if (Display != ValidatorDisplay.Static)
205                                         RegisterExpandoAttribute (ClientID, "display", Display.ToString ());
206                         }
207
208                         base.AddAttributesToRender (writer);
209                 }
210
211                 internal void RegisterExpandoAttribute (string controlId, string attributeName, string attributeValue)
212                 {
213                         RegisterExpandoAttribute (controlId, attributeName, attributeValue, false);
214                 }
215
216                 internal void RegisterExpandoAttribute (string controlId, string attributeName, string attributeValue, bool encode)
217                 {
218                         Page page = Page;
219                         if (page.ScriptManager != null)
220                                 page.ScriptManager.RegisterExpandoAttributeExternal (this, controlId, attributeName, attributeValue, encode);
221                         else
222                                 page.ClientScript.RegisterExpandoAttribute (controlId, attributeName, attributeValue, encode);
223                 }
224
225                 protected void CheckControlValidationProperty (string name, string propertyName)
226                 {
227                         Control control = NamingContainer.FindControl (name);
228                         PropertyDescriptor prop = null;
229
230                         if (control == null)
231                                 throw new HttpException (String.Format ("Unable to find control id '{0}'.", name));
232
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
238                 protected virtual bool ControlPropertiesValid ()
239                 {
240                         if (ControlToValidate.Length == 0) {
241                                 throw new HttpException (String.Format ("ControlToValidate property of '{0}' cannot be blank.", ID));
242                         }
243
244                         CheckControlValidationProperty (ControlToValidate, String.Empty);
245
246                         return true;
247                 }
248
249                 protected virtual bool DetermineRenderUplevel ()
250                 {
251                         if (!EnableClientScript)
252                                 return false;
253                         return UplevelHelper.IsUplevel (
254                                 System.Web.Configuration.HttpCapabilitiesBase.GetUserAgentForDetection (HttpContext.Current.Request));
255                 }
256
257                 protected abstract bool EvaluateIsValid ();
258
259                 protected string GetControlRenderID (string name)
260                 {
261                         Control control = NamingContainer.FindControl (name);
262                         if (control == null)
263                                 return null;
264
265                         return control.ClientID;
266                 }
267
268                 protected string GetControlValidationValue (string name)
269                 {
270                         Control control = NamingContainer.FindControl (name);
271
272                         if (control == null)
273                                 return null;
274
275                         PropertyDescriptor prop = BaseValidator.GetValidationProperty (control);
276                         if (prop == null)
277                                 return null;
278
279                         object o = prop.GetValue (control);
280
281                         if (o == null)
282                                 return String.Empty;
283                         
284                         if (o is ListItem)
285                                 return ((ListItem) o).Value;
286                         
287                         return o.ToString ();
288                 }
289
290                 public static PropertyDescriptor GetValidationProperty (object o)
291                 {
292                         PropertyDescriptorCollection props;
293                         System.ComponentModel.AttributeCollection col;
294
295                         props = TypeDescriptor.GetProperties (o);
296                         col = TypeDescriptor.GetAttributes (o);
297
298                         foreach (Attribute at in col) {
299                                 ValidationPropertyAttribute vpa = at as ValidationPropertyAttribute;
300                                 if (vpa != null && vpa.Name != null)
301                                         return props[vpa.Name];
302                         }
303
304                         return null;
305                 }
306
307                 protected internal override void OnInit (EventArgs e)
308                 {
309                         Page page = Page;
310                         /* according to an msdn article, this is done here */
311                         if (page != null) {
312                                 page.Validators.Add (this);
313                                 page.GetValidators (ValidationGroup).Add (this);
314                         }
315                         base.OnInit (e);
316                 }
317
318                 protected internal override void OnPreRender (EventArgs e)
319                 {
320                         base.OnPreRender (e);
321
322                         pre_render_called = true;
323                         
324                         ControlPropertiesValid ();
325
326                         render_uplevel = DetermineRenderUplevel ();
327                         if (render_uplevel)
328                                 RegisterValidatorCommonScript ();
329                 }
330
331                 protected internal override void OnUnload (EventArgs e)
332                 {
333                         Page page = Page;
334                         /* according to an msdn article, this is done here */
335                         if (page != null) {
336                                 page.Validators.Remove (this);
337                                 string validationGroup = ValidationGroup;
338                                 if (!String.IsNullOrEmpty (validationGroup))
339                                         page.GetValidators (ValidationGroup).Remove (this);
340                         }
341                         base.OnUnload (e);
342                 }
343
344                 protected void RegisterValidatorCommonScript ()
345                 {
346                         Page page = Page;
347                         if (page != null) {
348                                 if (page.ScriptManager != null) {
349                                         page.ScriptManager.RegisterClientScriptResourceExternal (this, typeof (BaseValidator), "WebUIValidation_2.0.js");
350                                         page.ScriptManager.RegisterClientScriptBlockExternal (this, typeof (BaseValidator), "ValidationInitializeScript", page.ValidationInitializeScript, true);
351                                         page.ScriptManager.RegisterOnSubmitStatementExternal (this, typeof (BaseValidator), "ValidationOnSubmitStatement", page.ValidationOnSubmitStatement);
352                                         page.ScriptManager.RegisterStartupScriptExternal (this, typeof (BaseValidator), "ValidationStartupScript", page.ValidationStartupScript, true);
353                                 } else if (!page.ClientScript.IsClientScriptIncludeRegistered (typeof (BaseValidator), "Mono-System.Web-ValidationClientScriptBlock")) {
354                                         page.ClientScript.RegisterClientScriptInclude (typeof (BaseValidator), "Mono-System.Web-ValidationClientScriptBlock",
355                                                                                        page.ClientScript.GetWebResourceUrl (typeof (BaseValidator), "WebUIValidation_2.0.js"));
356                                         page.ClientScript.RegisterClientScriptBlock (typeof (BaseValidator), "Mono-System.Web-ValidationClientScriptBlock.Initialize", page.ValidationInitializeScript, true);
357                                         page.ClientScript.RegisterOnSubmitStatement (typeof (BaseValidator), "Mono-System.Web-ValidationOnSubmitStatement", page.ValidationOnSubmitStatement);
358                                         page.ClientScript.RegisterStartupScript (typeof (BaseValidator), "Mono-System.Web-ValidationStartupScript", page.ValidationStartupScript, true);
359                                 }
360                         }
361                 }
362
363                 protected virtual void RegisterValidatorDeclaration ()
364                 {
365                         Page page = Page;
366                         if (page != null) {
367                                 if (page.ScriptManager != null) {
368                                         page.ScriptManager.RegisterArrayDeclarationExternal (this, "Page_Validators", String.Concat ("document.getElementById ('", ClientID, "')"));
369                                         page.ScriptManager.RegisterStartupScriptExternal (this, typeof (BaseValidator), ClientID + "DisposeScript",
370                                                                                           @"
371 document.getElementById('" + ClientID + @"').dispose = function() {
372     Array.remove(Page_Validators, document.getElementById('" + ClientID + @"'));
373 }
374 ", true);
375                                 } else
376                                         page.ClientScript.RegisterArrayDeclaration ("Page_Validators", String.Concat ("document.getElementById ('", ClientID, "')"));
377                         }
378                 }
379
380                 protected internal override void Render (HtmlTextWriter writer)
381                 {
382                         if (!IsEnabled && !EnableClientScript)
383                                 return;
384
385                         if (render_uplevel) {
386                                 /* according to an msdn article, this is done here */
387                                 RegisterValidatorDeclaration ();
388                         }
389
390                         bool render_tags = false;
391                         bool render_text = false;
392                         bool render_nbsp = false;
393                         bool v = IsValid;
394
395                         if (!pre_render_called) {
396                                 render_tags = true;
397                                 render_text = true;
398                         } else if (render_uplevel) {
399                                 render_tags = true;
400                                 render_text = Display != ValidatorDisplay.None;
401                         } else {
402                                 if (Display != ValidatorDisplay.None) {
403                                         render_tags = !v;
404                                         render_text = !v;
405                                         render_nbsp = v && Display == ValidatorDisplay.Static;
406                                 }
407                         }
408
409                         if (render_tags) {
410                                 AddAttributesToRender (writer);
411                                 writer.RenderBeginTag (HtmlTextWriterTag.Span);
412                         }
413
414                         if (render_text || render_nbsp) {
415                                 string text;
416                                 if (render_text) {
417                                         text = Text;
418                                         if (String.IsNullOrEmpty (text))
419                                                 text = ErrorMessage;
420                                 } else
421                                         text = " ";
422
423                                 writer.Write (text);
424                         }
425
426
427                         if (render_tags)
428                                 writer.RenderEndTag ();
429                 }
430
431                 /* the docs say "public sealed" here */
432                 public void Validate ()
433                 {
434                         if (IsEnabled && Visible)
435                                 IsValid = ControlPropertiesValid () && EvaluateIsValid ();
436                         else
437                                 IsValid = true;
438                 }
439         }
440 }