?
Solved

JavaScript in OnClientClick breaks ASP.NET Validation

Posted on 2011-10-18
11
Medium Priority
?
773 Views
Last Modified: 2012-05-12
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
Comment
Question by:megnin
  • 7
  • 3
11 Comments
 
LVL 28

Expert Comment

by:strickdd
ID: 36987470
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
 
LVL 1

Author Comment

by:megnin
ID: 36987483
I would if I knew how.  ;-)
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 1

Author Comment

by:megnin
ID: 36987551
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
 
LVL 28

Expert Comment

by:strickdd
ID: 36987659

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
 
LVL 1

Author Comment

by:megnin
ID: 36987769
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
 
LVL 28

Expert Comment

by:strickdd
ID: 36988072
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
 
LVL 1

Author Comment

by:megnin
ID: 36988760
Oh, okay.  I see.  I'll give it a try.
0
 
LVL 1

Author Comment

by:megnin
ID: 36993021
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
 
LVL 1

Accepted Solution

by:
megnin earned 0 total points
ID: 36995358
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
 
LVL 1

Author Closing Comment

by:megnin
ID: 37130072
This is the only solution that worked.
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In Part 1 (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_7849-Hex-Maze.html) we covered the hexagonal maze basics -- how the cells are represented in a JavaScript array and how the maze is displayed.  In this part, we'…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Suggested Courses
Course of the Month16 days, 11 hours left to enroll

862 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question