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