CheckBoxList Custom Validator
CodeKeep C# Feed Luglio 11th, 2008
Description: CheckBoxListValidatorLink: http://www.codekeep.net/snippets/8edecbca-9d9a-4fb4-8127-57170ecbc355.aspx
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Esc.Common
{
public class CheckBoxListValidator : BaseValidator
{
#region Fields
private CheckBoxList controlToValidate;
#endregion
#region Properties
protected CheckBoxList CheckBoxListToValidate
{
get
{
if (controlToValidate == null) controlToValidate = FindControl(ControlToValidate) as CheckBoxList;
return controlToValidate;
}
}
#endregion
#region Protected Methods
protected override void AddAttributesToRender(HtmlTextWriter writer)
{
base.AddAttributesToRender(writer);
// Add the client-side code (if needed).
if (RenderUplevel)
{
Page.ClientScript.RegisterExpandoAttribute(
ClientID,
"evaluationfunction",
"CheckBoxListValidatorEvaluateIsValid",
false);
}
}
protected override bool ControlPropertiesValid()
{
// make sure ControlToValidate is set.
if (ControlToValidate.Length == 0) throw new HttpException(string.Format(Resources.Messages.ControlToValidatePropertyCannotBeBlank, ID));
// ensure that the control being validated is a CheckBoxList.
if (CheckBoxListToValidate == null) throw new HttpException(string.Format(Resources.Messages.CheckBoxListValidatorCanOnlyValidateCheckBoxList));
// it's good.
return true;
}
protected bool EvaluateIsChecked()
{
CheckBoxList checkBoxList = CheckBoxListToValidate;
foreach (ListItem li in checkBoxList.Items)
{
// if any item is selected then the method returns true.
if (li.Selected) return true;
}
// no item was selected.
return false;
}
protected override bool EvaluateIsValid()
{
// only one test currently performed.
return EvaluateIsChecked();
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
// Register the client-side function using WebResource.axd (if needed)
// see: http://aspnet.4guysfromrolla.com/articles/080906-1.aspx
if (RenderUplevel && Page != null && !Page.ClientScript.IsClientScriptIncludeRegistered(GetType(), "Validators"))
{
Page.ClientScript.RegisterClientScriptInclude(
GetType(),
"Validators",
Page.ClientScript.GetWebResourceUrl(GetType(), "Esc.Common.Resources.Validators.js"));
}
}
#endregion
}
}