• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 839
  • Last Modified:

JavaScript in OnClientClick breaks ASP.NET Validation

Hi Experts,

I'm trying to ensure that at least one CheckBox is selected.  This checks the CheckBoxes okay, but breaks validation on the whole page. If I remove the CheckBox check validation works fine. With check() the page submits without any validation working.  How can I fix it so validation still works?

<asp:CheckBox ID="ResourceRoom" runat="server" Text="Resource Room" />
<asp:CheckBox ID="Workshop" runat="server" Text="Attend Workshop" />
<asp:CheckBox ID="Training" runat="server" Text="Training" />
<asp:CheckBox ID="GeneralInfo" runat="server" Text="General Information" />
<asp:CheckBox ID="Interview" runat="server" Text="Interview with an Employer" />

<asp:Button ID="Submit" runat="server" Text="Submit"  />

Open in new window

    <script type="text/javascript">
        function check() {
                var Inputs;
                Inputs = document.getElementsByTagName("input");
                for (var n = 0; n < Inputs.length; ++n)
                    if (Inputs[n].type == 'checkbox' && Inputs[n].checked)
                        return true;

                alert('Select at least one checkbox!');
                return false;
        }
    </script>

Open in new window

 Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
Submit.Attributes.Add("OnClick", "return check(); ")

Open in new window


I tried taking the return out and validation fired, but after the alert the page submitted without any checkboxes checked:
 Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
Submit.Attributes.Add("OnClick", " check(); ")

Open in new window

0
megnin
Asked:
megnin
  • 7
  • 3
1 Solution
 
strickddCommented:
You would probably have an easier time using a custom validator control and writing the client-side and server-side validation functions that way. It is sure to work with the exisiting validation.
0
 
megninAuthor Commented:
I would if I knew how.  ;-)
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

 
megninAuthor Commented:
Not helpful.  My script to check that at least one checkbox is checked works fine.  The problem is that any JavaScript in the onclick or OnClientClick of the Submit button breaks Validation on the page.  The CheckBox check works fine, but then the page will submit without any of the Validated TextBoxes being filled in.
0
 
strickddCommented:

Page:
function CheckClientSide(source, arguments)
{
var Inputs;
                Inputs = document.getElementsByTagName("input");
                for (var n = 0; n < Inputs.length; ++n)
                    if (Inputs[n].type == 'checkbox' && Inputs[n].checked)
                        arguments.IsValid = true;

                arguments.IsValid = false;
}

<asp:CustomValidator id="CustomValidator1"
           ControlToValidate="ResourceRoom"
           Display="Static"
           ErrorMessage="Check at least one"           ClientValidationFunction="CheckClientSide"
           OnServerValidate="CheckCheckboxCheck"
           runat="server"/>

Server-Side:
void CheckCheckboxCheck(object source, ServerValidateEventArgs args)
 {
    args.IsValid = (ResourceRoom.Checked || Workshop.Checked || Training.Checked || GeneralInfo.Checked || Interview.Checked);
 }
0
 
megninAuthor Commented:
Is the above adding validation to the CheckBoxes?
These are the fields where the validation is being broken:
            <tr>
                <td>
                    First Name:
                </td>
                <td>
                    <asp:TextBox ID="FirstName" runat="server" type="text" onkeypress="return alpha(event,letters)" />
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" 
                        ControlToValidate="FirstName" ErrorMessage="Required" ForeColor="Red"></asp:RequiredFieldValidator>
                </td>
                <td style="white-space:nowrap;">
                    Last Name:
                </td>
                <td colspan="3">
                    <asp:TextBox ID="LastName" runat="server" type="text" onkeypress="return alpha(event,letters)" />
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" 
                        ControlToValidate="LastName" ErrorMessage="Required" ForeColor="Red"></asp:RequiredFieldValidator>
                </td>

            </tr>

Open in new window

0
 
strickddCommented:
Yes, the code provided is for the checkboxes. You only have to add one custom validator to the page and it is set to validate all the checkboxes the way i laid it out.
0
 
megninAuthor Commented:
Oh, okay.  I see.  I'll give it a try.
0
 
megninAuthor Commented:
Hmmm, it says the control can not be validated.  What should I do?
Control 'ResourceRoom' referenced by the ControlToValidate property of 'CustomValidator1' cannot be validated. 
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.Web.HttpException: Control 'ResourceRoom' referenced by the ControlToValidate property of 'CustomValidator1' cannot be validated.

Source Error: 

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.  

Stack Trace: 


[HttpException (0x80004005): Control 'ResourceRoom' referenced by the ControlToValidate property of 'CustomValidator1' cannot be validated.]
   System.Web.UI.WebControls.BaseValidator.CheckControlValidationProperty(String name, String propertyName) +1779027
   System.Web.UI.WebControls.CustomValidator.ControlPropertiesValid() +35
   System.Web.UI.WebControls.BaseValidator.OnPreRender(EventArgs e) +36
   System.Web.UI.Control.PreRenderRecursiveInternal() +103
   System.Web.UI.Control.PreRenderRecursiveInternal() +175
   System.Web.UI.Control.PreRenderRecursiveInternal() +175
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2496

 


--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.1 

Open in new window

0
 
megninAuthor Commented:
This seems to do the Trick:
    <script type="text/javascript">
        function check() {
                var Inputs;
                Inputs = document.getElementsByTagName("input");
            var checkCount = 0;
            for (var n = 0; n < Inputs.length; ++n) {
                if (Inputs[n].type == 'checkbox' && Inputs[n].checked) {
                    checkCount++;
                }
            }
            if (checkCount < 1) {
                alert("Please select at least one Service.");
                return false;
            }
            return true;
        }
    </script>

Open in new window


After Googling the error I got on the CustomValidator it seems that you just can't add a validator to a CheckBox server side.  
0
 
megninAuthor Commented:
This is the only solution that worked.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

  • 7
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now