On a page I have a Repeater control, in the Repeater control I have an ItemTemplate which is CheckBox. As the Repeater is being bound it generates a CheckBox for each name in the contact list. I am trying to determine if the user selected at least 1 contact, I get the alert but the page posts back anyways. My CustomValidator looks like:
HTML
<asp:CustomValidator id="CustomValidator1" runat="server" ErrorMessage="CustomValidator" Display="None" ClientValidationFunction="CheckContacts" />
My JavaScript function (CheckContacts) liiks like:
jscript
function CheckContacts(source, args)
{
var ctrl = 'repContacts';
var cbName = 'cbSelect';
var objForm = document.form1;
var errorCount = 0;
var ctrlName = ctrl + '__ctl1_' + cbName;
var chkBox = document.getElementById(ctrlName);
if(chkBox == null)
{
alert ('There was an issue checking the *'+cbName+'* check box in the *'+ctrl+'* control');
return errorCount;
}
var isChecked = false;
var i = 1; // Notice the 1, its important to get the start number correct
ctrlName = ctrl + '__ctl' + i + '_'+ cbName;
var curItem = document.getElementById(ctrlName);
if(null == curItem)
{
alert ('It was null'); // something is wrong. Probably one of the 'Customize Values'
}
while (curItem != null)
{
//to check items inside the DataGrid/Repeater
//using the != null check should keep it from getting locked up
if (curItem.checked == true)
{
isChecked = true;
}
//increment i AND get the next control
i += 1 ;
ctrlName = ctrl + '__ctl' + i + '_'+
cbName;
curItem = document.getElementById(ctrlName);
}
if (isChecked == false)
{
source.errormessage = 'Your need to select at least 1 contact in your list';
errorCount+=1;
}
if (errorCount > 0)
{
args.IsValid = false;
}
else
{
args.IsValid = true;
}
}
Alone I get no alert if no contact is selected. If I add code to the code behind that adds an
onclick Event to my button like so:
csharp
btnWriteMessage.Attributes.Add("onclick", "return CheckContacts()");
I get my alert but the page still submits, which is what Im trying to stop. This is my first attempt (believe it or not) at using a CustomValidator control, so anyone got any ideas?