tags:

views:

23

answers:

1

I am working with a page that has a series of checkboxes that at least one box must be checked.

The validator fires when I click the submit button and if no checkboxes are checked indicates the validation has failed. However If I check one of the checkboxes the validation message does not go away until I click the submit button again.

If I was using this on a control in which I had specified the ControlToValidate and I fixed the validation issue the error message goes away immediately.

However in this case I am not setting the ControlToValidate due to the neeed to validate serveral independent controls.

So my question is can I cause a re-validation of the custom validator? For instance I would like to add on each checkbox a onclick="revalidate()" that would then force the validation to happen again.

Here is some sample code that I wrote to demonstrate the scenario.

<script type="text/javascript">
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"&gt;&lt;/script&gt;
    function IsOneCheckboxChecked(sender, args) {
        if (!$('[id$=checkBox1]').attr('checked') &&
    !$('[id$=checkBox2]').attr('checked')) {
            args.IsValid = false;
        }
        else {
            args.IsValid = true;
        }
    }
</script>



<asp:CheckBox ID="checkBox1" runat="server" />
<br />
<asp:CheckBox ID="checkBox2" runat="server" />
<br />
<asp:CustomValidator ID="customValidatorMustBeOnCheckboxChecked" 
    runat="server" ClientValidationFunction="IsOneCheckboxChecked"
    ErrorMessage="You must select at least one checkbox option" 
    OnServerValidate="customValidatorMustBeOnCheckboxChecked_ServerValidate" />
<br />
<br />
<asp:Button ID="buttonSubmit" runat="server" Text="Submit" />
A: 

Well I was able to solve the issue by finding the span that the control validator creates and in my revalidate method hide or expose the error message. However I would like to think something better exists?

I created a blog entry on this at:

http://coding.infoconex.com/post/ASPNET-CustomValidator-that-validates-multiple-controls-using-both-Server-Side-and-Client-Side-scripting.aspx

 function Revalidate() {
        if (!$('[id$=checkBox1]').attr('checked')
        && !$('[id$=checkBox2]').attr('checked')) {
            var control = $('[id$=customValidatorMustBeOnCheckboxChecked]');
           control.css('display', 'inline');
        }
        else {
            var control = $('[id$=customValidatorMustBeOnCheckboxChecked]');
            control.css('display', 'none');
        }
    }

<asp:CheckBox ID="checkBox1" runat="server" onclick="Revalidate()" />
<br />
<asp:CheckBox ID="checkBox2" runat="server" onclick="Revalidate()" />
Jim Scott
Surely there has to be a better way? No?
Jim Scott