1using System;
2using System.Web;
3using System.Web.UI;
4using System.Web.UI.WebControls;
5
6namespace Esc.Common
7{
8 public class CheckBoxListValidator : BaseValidator
9 {
10 #region Fields ...
11
12
13 private CheckBoxList controlToValidate;
14 #endregion
15 #region Properties ...
16
17
18 protected CheckBoxList CheckBoxListToValidate
19 {
20 get
21 {
22 if (controlToValidate == null) controlToValidate = FindControl(ControlToValidate) as CheckBoxList;
23
24 return controlToValidate;
25 }
26 }
27 #endregion
28 #region Protected Methods ...
29
30
31 protected override void AddAttributesToRender(HtmlTextWriter writer)
32 {
33 base.AddAttributesToRender(writer);
34
35 // Add the client-side code (if needed).
36 if (RenderUplevel)
37 {
38 Page.ClientScript.RegisterExpandoAttribute(
39 ClientID,
40 "evaluationfunction",
41 "CheckBoxListValidatorEvaluateIsValid",
42 false);
43 }
44 }
45
46 protected override bool ControlPropertiesValid()
47 {
48 // make sure ControlToValidate is set.
49 if (ControlToValidate.Length == 0) throw new HttpException(string.Format(Resources.Messages.ControlToValidatePropertyCannotBeBlank, ID));
50
51 // ensure that the control being validated is a CheckBoxList.
52 if (CheckBoxListToValidate == null) throw new HttpException(string.Format(Resources.Messages.CheckBoxListValidatorCanOnlyValidateCheckBoxList));
53
54 // it's good.
55 return true;
56 }
57
58 protected bool EvaluateIsChecked()
59 {
60 CheckBoxList checkBoxList = CheckBoxListToValidate;
61
62 foreach (ListItem li in checkBoxList.Items)
63 {
64 // if any item is selected then the method returns true.
65 if (li.Selected) return true;
66 }
67
68 // no item was selected.
69 return false;
70 }
71
72 protected override bool EvaluateIsValid()
73 {
74 // only one test currently performed.
75 return EvaluateIsChecked();
76 }
77
78 protected override void OnPreRender(EventArgs e)
79 {
80 base.OnPreRender(e);
81
82 // Register the client-side function using WebResource.axd (if needed)
83 // see: http://aspnet.4guysfromrolla.com/articles/080906-1.aspx
84 if (RenderUplevel && Page != null && !Page.ClientScript.IsClientScriptIncludeRegistered(GetType(), "Validators"))
85 {
86 Page.ClientScript.RegisterClientScriptInclude(
87 GetType(),
88 "Validators",
89 Page.ClientScript.GetWebResourceUrl(GetType(), "Esc.Common.Resources.Validators.js"));
90 }
91 }
92 #endregion
93 }
94}