我已經爲checkBoxList驗證創建了自定義類:
這是我的自定義類代碼。
namespace Custom.Validators
{
public class RFVCBoxList : BaseValidator
{
private const string SCRIPTBLOCK = "RFV4CL";
protected override bool ControlPropertiesValid()
{
Control ctrl = FindControl(ControlToValidate);
if (ctrl != null)
{
CheckBoxList _listctrl = (CheckBoxList)ctrl;
return (_listctrl != null);
}
else
return false;
}
protected override bool EvaluateIsValid()
{
return EvaluateIsChecked();
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
if (EnableClientScript) { this.ClientScript(); }
}
private void ClientScript()
{
StringBuilder sb_Script = new StringBuilder();
sb_Script.Append("<script language=\"javascript\">");
sb_Script.Append("\r");
sb_Script.Append("\r");
sb_Script.Append("function cb_verify(sender) {");
sb_Script.Append("\r");
sb_Script.Append("var val = document.getElementById(document.getElementById(sender.id).controltovalidate);");
sb_Script.Append("\r");
sb_Script.Append("var col = val.getElementsByTagName(\"*\");");
sb_Script.Append("\r");
sb_Script.Append("if (col != null) {");
sb_Script.Append("\r");
sb_Script.Append("for (i = 0; i < col.length; i++) {");
sb_Script.Append("\r");
sb_Script.Append("if (col.item(i).tagName == \"INPUT\") {");
sb_Script.Append("\r");
sb_Script.Append("if (col.item(i).checked) {");
sb_Script.Append("\r");
sb_Script.Append("\r");
sb_Script.Append("return true;");
sb_Script.Append("\r");
sb_Script.Append("}");
sb_Script.Append("\r");
sb_Script.Append("}");
sb_Script.Append("\r");
sb_Script.Append("}");
sb_Script.Append("\r");
sb_Script.Append("\r");
sb_Script.Append("\r");
sb_Script.Append("return false;");
sb_Script.Append("\r");
sb_Script.Append("}");
sb_Script.Append("\r");
sb_Script.Append("}");
sb_Script.Append("\r");
sb_Script.Append("</script>");
Page.ClientScript.RegisterClientScriptBlock(GetType(), SCRIPTBLOCK, sb_Script.ToString());
Page.ClientScript.RegisterExpandoAttribute(ClientID, "evaluationfunction", "cb_verify");
}
private bool EvaluateIsChecked()
{
CheckBoxList _cbl = ((CheckBoxList)FindControl(ControlToValidate));
foreach (ListItem li in _cbl.Items)
{
if (li.Selected)
{
return true;
}
}
return false;
}
public RFVCBoxList()
{
//
// TODO: Add constructor logic here
//
}
}
}
您可以像爲
<%@ Register TagPrefix="CC1" Namespace="Custom.Validators" %>
之後,你可以設置驗證照常
<CC1:RFVCBoxList ID="rfvContactType" runat="server" ControlToValidate="chkContactType"
Display="None" ErrorMessage="Please select contact type" SetFocusOnError="True"
ValidationGroup="Photographer"></CC1:RFVCBoxList>
希望這將有助於你頁面上註冊自定義類。
可能重複 - 驗證用戶選擇至少一個複選框(http://stackoverflow.com/questions/1146234/asp-net-checkboxlist-validate-user-chooses-at-least-one-checkbox) – RPM1984 2011-05-04 12:28:59