CheckBox and CheckBoxList Validators for multiple checkboxlists
Posted by ken zheng on June 27, 2008
Use 4Guys Creating CheckBox and CheckBoxList Validators in ASP.NET 2.0, you can build a custom validator control for your Checkbox and checkboxlist. But if you have more than one CheckBoxList in your page, the validator will not work because the Javascript will only apply to one control.
What you can do is modify the validator class to create an individual javascript for each validator.
In GenerateClientValidation method
change to:
….
Attributes["evaluationfunction"] = "VerifyItemSelected_" + <strong>ControlToValidate</strong>;
StringBuilder scriptBuilder = new StringBuilder();
scriptBuilder.Append(@"<script language='javascript'>");
scriptBuilder.Append(string.Format("function VerifyItemSelected_{0}", <strong>ControlToValidate</strong>));
scriptBuilder.Append(@"() {");
scriptBuilder.Append(string.Format("var targetControlName = document.getElementById('{0}')", this.ClientID));
scriptBuilder.Append(@".controltovalidate;");
…..
Finally,
Page.ClientScript.RegisterClientScriptBlock(typeof(CheckBoxListValidator), “CustomCheckboxListValidationScript_” + ControlToValidate, scriptBuilder.ToString());
By changing the code, we can ensure all the validator scripts are being registered.
Chad Rosenthal said
I’m looking at your code, and trying to implement it, but it is not exactly clear to me where the lines of code should go. It looks like the finally Page.ClientScript should go in the PreRender, but is that where the scriptBuilders go also?
Would love to see your code, if you don’t mind.
Thanks