Disabling validations

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • user1980
    New Member
    • Dec 2009
    • 112

    Disabling validations

    Brief overview of my problem......I have certain text boxes(say, txtbox2) in a page that have to be filled only if certain other text boxes(say, txtbox1) are filled. For this, I have disabled the requiredfield validators for txtbox2 in the asp.net code and then wrote a javascript to enable these text boxes on the required conditions. All this works well....

    In my submit button I have written this,

    Code:
    OnClientClick="if(Page_ClientValidate()) return Check();"
    my javascript

    Code:
    Function Check()
    {    
            var Valtxtbox1 = document.getElementById("<%=txtbox1.ClientID%>").value;  
                var Valtxtbox2 = document.getElementById("<%=txtbox2.ClientID%>").value;  
       
                
                if((Valtxtbox1 != '') && (Valtxtbox2 == ''))
                {
                
                    alert('Please enter in txtbox2');
                    ValidatorEnable(document.getElementById('required_txtbox2'), true); 
                    return false;
                }
                
                if ((Valtxtbox2 != '') && (Valtxtbox1 == ''))
                {
                    if(parseInt(Valtxtbox2))
                    {
                    alert('Please enter in txtbox1');
                     ValidatorEnable(document.getElementById('required_txtbox1'), true); 
                    }
                    else
                    {
                    document.getElementById("<%=txtbox1.ClientID%>").value = '';
                    }
                    return false;
                }
                
               if ((Valtxtbox1 == '') && (Valtxtbox2 == ''))
                {  
                   ValidatorEnable(document.getElementById('required_txtbox1'), false);
                   ValidatorEnable(document.getElementById('required_txtbox2'), false);
                } 
    
    return true;
    
    }
    this validates the page and then goes to the javascript for other validations. My problem now is, if the user fills in a txtbox1 it would enable the requiredfield validator for the other txtbox2.
    But if the user decides not to fill the txtbox2 and deletes text from txtbox1, still the txtbox2's requiredfield validator remains enabled and the Page_ClientVali date throws the error that the txtbox2 has to be filled.
    In my javascript I am enabling and also disabling the requriedfield validators on the specifed conditions.
    But since the Page_ClientVali date does not go to the javascript, it throws this error..which is quite logical...as it is validating the page first and the txtbox2's is a requiredfield.. ..

    I have been struggling for a logic which would help me disable the validators when the txtbox1 is filled and then again deleted....can somebody please guide me on this..thank you..
  • Frinavale
    Recognized Expert Expert
    • Oct 2006
    • 9749

    #2
    Hmm...consider the following:

    Code:
    If(TextBox1.value == ""){
      alert('Please enter a value for TextBox1");
    }Else If(TextBox2.value ==""){
      alert("Please enter a value for TextBox2");
    }Else{
      //in this case both TextBox1 and TextBox2 have values in them
      //you can do further validation on what was entered if you need to
      // or you can just get rid of this case.
    }
    This code checks to see if a value has been entered into TextBox1...if no value has been entered it displays a message stating that the user needs to enter a value. If TextBox1 has data in it, it checks to see if TextBox2 has data entered into it...if TextBox2 has nothing in it (and TextBox1 does) it displays a message stating that the user needs to enter a value for TextBox2.

    -Frinny

    Comment

    • user1980
      New Member
      • Dec 2009
      • 112

      #3
      thank you for the reply but sorry for the delay in the response...
      If I implement your case I would still have the problem. The thing is I would prompt the user to enter in textbox2 if textbox1 is filled. But if the user does not enter and try to submit the page it would still take it because the page.validate is ture. the javascript is just alerting the user but not forcing him to enter. That is the reason I am suing the required field validator to ensure the Page.validate is false when the user does not enter the text.

      I am struck at this point. I am trying to modify my existing javascript but to no avail.

      Thank you for your time.

      Comment

      • Frinavale
        Recognized Expert Expert
        • Oct 2006
        • 9749

        #4
        I've never really played a lot with the validators in ASP.NET.
        Have you tried using the cases that I outlined in the if/elseif/else block to enable/disable the validators instead of displaying alerts?

        -Frinny

        Comment

        • user1980
          New Member
          • Dec 2009
          • 112

          #5
          yeah..I did try that too. The problem with that is, it disables the validators but first prompts me to enter the value and when I hit ok then submits the page.
          I have added this in the submit button properties.
          Code:
          OnClientClick="if(Page_ClientValidate()) {Check();} else {disable();}"
          In the disable function I am disabling the validators, but the function is entered only after prompting the error once, which should not happen. It is supposed to enter the function directly.

          Comment

          • Frinavale
            Recognized Expert Expert
            • Oct 2006
            • 9749

            #6
            Honestly sometimes I think that validators are more of a headache than they're worth sometime. They are great for quick, uncomplicated scenarios but your scenario is not uncomplicated.

            Since you're already implementing JavaScript to help with the validation why not take it one step further: do all of your validation using JavaScript instead of relying on the validators (which just use JavaScript anyways) to do the work for you?

            (By the way, you should always be doing server side validation even if you're using client side validation... I'm sure you know this but I think it's good to reiterate this fact)

            -Frinny

            Comment

            • user1980
              New Member
              • Dec 2009
              • 112

              #7
              thank you...I will try using javascript for all the validations. I think that would solve my issue. And I am using serve side validation for the values entered into the textboxes but for the required field validations, i had to use this client side javascript.

              Comment

              • Frinavale
                Recognized Expert Expert
                • Oct 2006
                • 9749

                #8
                :) sounds like you know what you're doing :)

                If you need help just ask.

                Comment

                • liawcv
                  New Member
                  • Jan 2009
                  • 33

                  #9
                  RequiredValidat or may not suit your needs. Consider CustomValidator . Assign its "ClientValidati onFunction" property to the name of the JavaScript function that you created (i.e. client-side validation). Double-click on it, and write codes for its server-side validation.

                  I assume that you want either both TextBoxes (namely TextBox1 and TextBox2) empty or both filled. The following are codes I wrote for both client-side validation and server-side validation on my test case:

                  Code:
                  // JavaScript : Client-side validation
                  function ClientValidate(sender, args) {
                      var txt1 = document.getElementById("<%= TextBox1.ClientID %>");
                      var txt2 = document.getElementById("<%= TextBox2.ClientID %>");
                      if ((txt1.value != "" && txt2.value == "") ||
                          (txt1.value == "" && txt2.value != "")) {
                          args.IsValid = false;
                      } else {
                          args.IsValid = true;
                      }
                  }
                  Code:
                  // C# : Server-side validation
                  protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
                  {
                      if ((TextBox1.Text != "" && TextBox2.Text == "") ||
                          (TextBox1.Text == "" && TextBox2.Text != ""))
                      {
                          args.IsValid = false;
                      }
                      else
                      {
                          args.IsValid = true;
                      }
                  }
                  Hope it helps. : )

                  Comment

                  • user1980
                    New Member
                    • Dec 2009
                    • 112

                    #10
                    thank you so much but i do not know what is wrong with my code..it does not validate the errors. Please find my code below

                    Code:
                    <html xmlns="http://www.w3.org/1999/xhtml" >
                    <head id="Head1" runat="server">
                        <title></title>
                        
                        <script language="javascript">
                    
                            function ClientValidate(sender, args) {
                                var txt1 = document.getElementById("<%= gpa.ClientID %>");
                                var txt2 = document.getElementById("<%= classgpa.ClientID %>");
                                if ((txt1.value != "" && txt2.value == "") ||
                            (txt1.value == "" && txt2.value != "")) {
                                    args.IsValid = false;
                                } else {
                                    args.IsValid = true;
                                }
                            }
                    
                    </head>
                    <body>
                        <form id="form1" runat="server">
                        <div>
                                 <asp:ValidationSummary ID="ValidationSummary1" runat="server" 
                                          Font-Names="Arial" Font-Size="Small" 
                                          HeaderText="Please correct the following errors." ShowMessageBox="true" 
                                          ShowSummary="false" ValidationGroup="Submit" />
                        <table style="width:95%; height:100%">
                                              
                                                      <tr>
                                                         <td style="width:40%">Title:</td>
                                                         <td valign="top">
                                                           <asp:RadioButtonList ID="Sex" runat="server" AppendDataBoundItems="true" CellPadding="0" CellSpacing="0" RepeatDirection="Horizontal" RepeatLayout="Flow" class="nonbox">
                                                                 <asp:ListItem Value="2">Mr.</asp:ListItem>
                                                                 <asp:ListItem Value="1">Ms.</asp:ListItem>
                                                           </asp:RadioButtonList>
                                                           <asp:RequiredFieldValidator ID="RequiredFieldValidator_Sex" runat="server" 
                                                                 ErrorMessage="Please select a title" Display="Dynamic" 
                                                                 ControlToValidate="Sex" SetFocusOnError="True" ValidationGroup="Submit">*</asp:RequiredFieldValidator>
                                                         </td>
                                                      </tr>
                                              
                                                      <tr>
                                                        <td >First Name:</td>
                                                        <td><asp:TextBox ID="first" runat="server" Width="225px"></asp:TextBox>
                                                            <asp:RequiredFieldValidator ID="RequiredFieldValidator_first" runat="server" ErrorMessage="Please enter your first name" 
                                                                  ControlToValidate="first"  Display="Dynamic" SetFocusOnError="True" 
                                                                ValidationGroup="Submit">*</asp:RequiredFieldValidator>
                                                         </td>
                                                      </tr>
                                                      </table>
                        
                        <asp:Label ID="errmsg" runat="server" Text="" Visible="false" Enabled="false" Font-Bold="true" ForeColor="Red"></asp:Label>
                        <h3>Additional Information</h3>
                                                  
                                                         <asp:CheckBoxList ID="additionalinfo" runat="server" AppendDataBoundItems="True" 
                                                                CellPadding="0" CellSpacing="0" RepeatLayout="Flow" AutoPostBack="true"
                                                          onselectedindexchanged="additionalinfo_SelectedIndexChanged" CausesValidation="false">
                                                        
                                                         <asp:ListItem Value="256" Text="Honors Program" />
                                                         </asp:CheckBoxList>
                             <asp:Panel ID="Panel2" runat="server" Visible="false" >
                                                 
                                                
                    	                        <h3>GPA</h3>
                    	                        <!--GPA and class rank details-->
                    	                         <table style="width:95%;height:100%;border:0" width="100%">
                    	                                 <tr>
                    	                                        <td style="border:0">If weighted, check here&nbsp;<asp:CheckBox 
                                                                        ID="weightedGPA" runat="server" oncheckedchanged="weightedGPA_CheckedChanged" AutoPostBack="true" /> </td>
                    	                                 </tr>
                    	                                 <tr>
                    	                                        <td style="border:0">GPA&nbsp;
                                                                    <asp:TextBox ID="gpa" runat="server" Width="60px"></asp:TextBox>
                                                                   <%-- <asp:RequiredFieldValidator ID="required_gpa" runat="server" 
                                                                        ControlToValidate="gpa" Display="Dynamic" 
                                                                        Enabled="false"  ErrorMessage="Please enter the GPA"
                                                                        SetFocusOnError="true" ValidationGroup="Submit"></asp:RequiredFieldValidator>--%><br />
                                                                    <asp:RangeValidator ID="validator_gpa" runat="server" ErrorMessage="Please enter a valid number for GPA" ControlToValidate="gpa" MinimumValue="0" MaximumValue="10" Type="Double" SetFocusOnError="True"></asp:RangeValidator>    
                                                                    <asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="gpa" 
                                                                        ErrorMessage="Please enter the GPA and the highest GPA" 
                                                                        ClientValidationFunction="ClientValidate" 
                                                                        onservervalidate="CustomValidator1_ServerValidate"></asp:CustomValidator>   
                                                                </td>
                                                           </tr>
                                                           <tr>
                                    	                        <td style="border:0"> Highest Possible GPA in your class 
                                                                    <asp:TextBox ID="classgpa" runat="server" Width="70px"></asp:TextBox>
                                                                    <%--<asp:RequiredFieldValidator ID="required_classgpa" runat="server" Enabled="false"
                                                                        ControlToValidate="classgpa" ErrorMessage="Please enter the highest GPA in the class"
                                                                         SetFocusOnError="true" ValidationGroup="Submit"></asp:RequiredFieldValidator>--%><br />
                                                                    <asp:RangeValidator ID="validator_classgpa" runat="server" Display="Dynamic" 
                                                                        ErrorMessage="Please enter a valid number for GPA" ControlToValidate="classgpa" 
                                                                        MinimumValue="0" MaximumValue="10" Type="Double" SetFocusOnError="True" 
                                                                        ValidationGroup="Submit"></asp:RangeValidator><br />
                                                                    <asp:CompareValidator ID="compare_gpa" runat="server" ErrorMessage="GPA should be less than or equal to class highest GPA"
                                                                     ControlToValidate="classgpa" Operator="GreaterThanEqual" Type="Double" ValidationGroup="Submit" Display="Dynamic" 
                                                                        Enabled="false" ControlToCompare="gpa" SetFocusOnError="True"></asp:CompareValidator> 
                                                                      
                    	                                        </td>
                    	                                 </tr>
                    	                                 
                    	                                 <tr>
                    	                                         <td style="border:0">Class rank&nbsp; 
                                                                    <asp:TextBox ID="classrank" runat="server" Width="50px"></asp:TextBox>
                                                                     &nbsp; of &nbsp;
                                                                    <asp:TextBox ID="totalclass" runat="server" Width="60px"></asp:TextBox>
                                                                  <asp:RequiredFieldValidator ID="required_classrank" runat="server" ErrorMessage="Please enter a valid number for class rank" 
                                                                      ControlToValidate="classrank" Enabled="false" SetFocusOnError="True" ValidationGroup="Submit" >*</asp:RequiredFieldValidator>
                                                                    <br />
                                                                    <asp:RequiredFieldValidator ID="required_totalclass" runat="server" ErrorMessage="Please enter a valid number for total class rank"
                                                                      ControlToValidate="totalclass" Enabled="false" SetFocusOnError="True" ValidationGroup="Submit" >*</asp:RequiredFieldValidator><br />
                                                                    <asp:RangeValidator ID="classrank_range" runat="server" 
                                                                         ErrorMessage="Please enter a valid number value for class rank." ControlToValidate="classrank"  
                                                                         MaximumValue="10000" MinimumValue="0" Type="Double"></asp:RangeValidator><br />
                                                                     <asp:RangeValidator ID="totalrank1_range" runat="server" ErrorMessage="Please enter a valid number value for the total rank." ControlToValidate="totalclass" 
                                                                         MaximumValue="10000" MinimumValue="0" Type="Double" ></asp:RangeValidator><br />
                                                                      <asp:CompareValidator ID="compare_rank" runat="server" ErrorMessage="Class rank has to be equal to or lower than the total class rank"
                                                                     ControlToValidate="totalclass" Operator="GreaterThanEqual" Type="Integer" ValidationGroup="Submit"
                                                                        Enabled="false" ControlToCompare="classrank" SetFocusOnError="True"></asp:CompareValidator>    
                                                                 </td>
                                                         </tr>
                                          </table>
                                          
                                          </asp:Panel>
                        </div>
                         
                        <table style="width:30%; height:100%">
                                                <tr>
                                                    <td>
                                                        <asp:Button ID="Submit" runat="server" Text="Submit Form" 
                                                            onclick="Submit1_Click"  ValidationGroup="Submit" />
                                                   </td>
                                                    <td>
                                                        <asp:Button ID="Reset" runat="server" Text="Reset Form" 
                                                            OnClientClick="Reset1_Click" onclick="Reset_Click"/></td>
                                                 </tr>
                                            </table> 
                        
                        </form>
                    </body>
                    </html>
                    my code behind page,

                    Code:
                    namespace WebApplication3
                    {
                        public partial class WebForm4 : System.Web.UI.Page
                        {
                             protected void Page_Load(object sender, EventArgs e)
                            {
                    
                    
                            }
                    
                            protected void Submit1_Click(object sender, EventArgs e)
                            {
                    
                                if (Page.IsValid)
                                    Response.Redirect("http://www.google.com");
                    
                                else
                                {
                                    errmsg.Enabled = true;
                                    errmsg.Visible = true;
                                    errmsg.Text = "Errors";
                    
                                }
                    
                            }
                    
                            protected void additionalinfo_SelectedIndexChanged(object sender, EventArgs e)
                            {
                                if (additionalinfo.Items[0].Selected == true)
                                {
                                    Panel2.Visible = true;
                                    SetFocus(weightedGPA);
                                }
                                else
                                {
                                    Panel2.Visible = false;
                                    SetFocus(Submit);
                                }
                            }
                            protected void Reset_Click(object sender, EventArgs e)
                            {
                                Server.Transfer("WebForm3.aspx");
                            }
                    
                            protected void weightedGPA_CheckedChanged(object sender, EventArgs e)
                            {
                                //if (weightedGPA.Checked == true)
                                //{
                    
                                //    required_gpa.Enabled = true;
                                //    required_gpa.SetFocusOnError = true;
                    
                                //    required_classgpa.Enabled = true;
                                //    required_classgpa.SetFocusOnError = true;
                    
                                //}
                                //else
                                //{
                                //    required_gpa.Enabled = false;
                                //    required_classgpa.Enabled = false;
                    
                                //}
                            }
                    
                            protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
                            {
                                if ((gpa.Text != "" && classgpa.Text == "") ||
                            (gpa.Text == "" && classgpa.Text != ""))
                                {
                                    args.IsValid = false;
                                }
                                else
                                {
                                    args.IsValid = true;
                                }
                            }
                        }
                        }
                    I am working on asp.net 2.0. I am not sure what is wrong whit my code. I have been working different options but to no avail.

                    Here is my code that uses required field validators.

                    Code:
                    <html xmlns="http://www.w3.org/1999/xhtml" >
                    <head runat="server">
                        <title></title>
                        
                        <script>
                    
                            function Check() {
                                alert("checking");
                    
                                // GPA and highest GPA in the class
                                var Valgpa = document.getElementById("<%=gpa.ClientID%>").value;
                                var Valclassgpa = document.getElementById("<%=classgpa.ClientID%>").value;
                    
                    
                                if ((Valgpa != '') && (Valclassgpa == '')) {
                                 //   alert("1");
                                    if (parseFloat(Valgpa)) {
                                   //     alert("2");
                                        alert('Please enter the highest GPA in class');
                                        ValidatorEnable(document.getElementById('required_classgpa'), true);
                                        document.form2.classgpa.focus();
                                    }
                                    else {
                                        document.getElementById("<%=gpa.ClientID%>").value = '';
                                    }
                                    return false;
                                }
                    
                                if ((Valclassgpa != '') && (Valgpa == '')) {
                                    if (parseFloat(Valclassgpa)) {
                                        alert('Please enter the GPA');
                                        ValidatorEnable(document.getElementById('required_gpa'), true);
                                        document.form2.gpa.focus();
                                    }
                                    else {
                                        document.getElementById("<%=classgpa.ClientID%>").value = '';
                                    }
                                    return false;
                                }
                    
                                if ((Valgpa != '') && (Valclassgpa != '')) {
                                    if (parseFloat(Valgpa) && parseFloat(Valclassgpa)) {
                                        if (Valgpa > Valclassgpa) {
                                            alert('GPA should be less than or equal to class highest GPA');
                                            document.form2.classgpa.focus();
                                            ValidatorEnable(document.getElementById('compare_gpa'), true);
                                            return false;
                                        }
                                    }
                                }
                    
                                if ((Valgpa == '') && (Valclassgpa == '')) {
                                    ValidatorEnable(document.getElementById('required_classgpa'), false);
                                    ValidatorEnable(document.getElementById('required_gpa'), false);
                    
                                }
                    
                    
                                //Class rank and total rank
                                var Valrank = document.getElementById("<%=classrank.ClientID%>").value;
                                var Valtotalclass = document.getElementById("<%=totalclass.ClientID%>").value;
                    
                                if ((Valrank != '') && (Valtotalclass == '')) {
                                    alert('ges here');
                                    if (parseInt(Valrank)) {
                                        alert('Please enter a valid number for total class rank');
                                        ValidatorEnable(document.getElementById('required_totalclass'), true);
                                        document.form2.totalclass.focus();
                                    }
                                    else {
                                        document.getElementById("<%=classrank.ClientID%>").value = '';
                                    }
                                    return false;
                                }
                    
                                if ((Valtotalclass != '') && (Valrank == '')) {
                                    if (parseInt(Valtotalclass)) {
                                        alert('Please enter a valid number for class rank');
                                        ValidatorEnable(document.getElementById('required_classrank'), true);
                                        document.form2.classrank.focus();
                                    }
                                    else {
                                        document.getElementById("<%=totalclass.ClientID%>").value = '';
                                    }
                                    return false;
                                }
                                if ((Valrank != '') && (Valtotalclass != '')) {
                                    if (parseInt(Valrank) && parseInt(Valtotalclass)) {
                                        if (Valrank > Valtotalclass) {
                                            alert('Class rank has to be equal to or lower than the total class rank');
                                            ValidatorEnable(document.getElementById('compare_rank'), true);
                                            document.form2.classrank.focus();
                                            return false;
                                        }
                                    }
                                }
                    
                                if ((Valrank == '') && (Valtotalclass == '')) {
                                    ValidatorEnable(document.getElementById('required_totalclass'), false);
                                    ValidatorEnable(document.getElementById('required_classrank'), false);
                                }
                                return true;
                            }
                    
                    
                    
                            function disable_validations() {
                                alert("disable");
                    
                                var Valgpa = document.getElementById("<%=gpa.ClientID%>").value;
                                var Valclassgpa = document.getElementById("<%=classgpa.ClientID%>").value;
                    
                                if ((Valgpa == '') && (Valclassgpa == '')) {
                                    alert("1");
                                    ValidatorEnable(document.getElementById('required_classgpa'), false);
                                    ValidatorEnable(document.getElementById('required_gpa'), false);
                                }
                                else {
                                    if ((Valgpa != '') && (Valclassgpa == '')) {
                                        ValidatorEnable(document.getElementById('required_classgpa'), true);
                                        alert('Please enter the highest GPA in class');
                                    }
                                    if ((Valgpa == '') && (Valclassgpa != '')) {
                                        ValidatorEnable(document.getElementById('required_gpa'), true);
                                        alert('Please enter the GPA');
                                    }
                                    //  return false;
                    
                                }
                    
                    
                                var Valrank = document.getElementById("<%=classrank.ClientID%>").value;
                                var Valtotalclass = document.getElementById("<%=totalclass.ClientID%>").value;
                    
                    
                                if ((Valrank == '') && (Valtotalclass == '')) {
                                    alert("2");
                                    ValidatorEnable(document.getElementById('required_totalclass'), false);
                                    ValidatorEnable(document.getElementById('required_classrank'), false);
                                }
                                else {
                                    if ((Valrank != '') && (Valtotalclass == '')) {
                                        ValidatorEnable(document.getElementById('required_totalclass'), true);
                                        alert('Please enter a valid number for class rank');
                                    }
                                    if ((Valrank == '') && (Valtotalclass != '')) {
                                        ValidatorEnable(document.getElementById('required_classrank'), true);
                                        alert('Please enter a valid number for total class rank');
                                    }
                                    //     return false;
                                }
                                return true;
                            }
                        </script>
                    </head>
                    <body>
                        <form id="form1" runat="server">
                        <div>
                                 <asp:ValidationSummary ID="ValidationSummary1" runat="server" 
                                          Font-Names="Arial" Font-Size="Small" 
                                          HeaderText="Please correct the following errors." ShowMessageBox="true" 
                                          ShowSummary="false" ValidationGroup="Submit" />
                        <table style="width:95%; height:100%">
                                              
                                                      <tr>
                                                         <td style="width:40%">Title:</td>
                                                         <td valign="top">
                                                           <asp:RadioButtonList ID="Sex" runat="server" AppendDataBoundItems="true" CellPadding="0" CellSpacing="0" RepeatDirection="Horizontal" RepeatLayout="Flow" class="nonbox">
                                                                 <asp:ListItem Value="2">Mr.</asp:ListItem>
                                                                 <asp:ListItem Value="1">Ms.</asp:ListItem>
                                                           </asp:RadioButtonList>
                                                           <asp:RequiredFieldValidator ID="RequiredFieldValidator_Sex" runat="server" 
                                                                 ErrorMessage="Please select a title" Display="Dynamic" 
                                                                 ControlToValidate="Sex" SetFocusOnError="True" ValidationGroup="Submit">*</asp:RequiredFieldValidator>
                                                         </td>
                                                      </tr>
                                              
                                                      <tr>
                                                        <td >First Name:</td>
                                                        <td><asp:TextBox ID="first" runat="server" Width="225px"></asp:TextBox>
                                                            <asp:RequiredFieldValidator ID="RequiredFieldValidator_first" runat="server" ErrorMessage="Please enter your first name" 
                                                                  ControlToValidate="first"  Display="Dynamic" SetFocusOnError="True" 
                                                                ValidationGroup="Submit">*</asp:RequiredFieldValidator>
                                                         </td>
                                                      </tr>
                                                      </table>
                        
                        <asp:Label ID="errmsg" runat="server" Text="" Visible="false" Enabled="false" Font-Bold="true" ForeColor="Red"></asp:Label>
                        <h3>Additional Information</h3>
                                                  
                                                         <asp:CheckBoxList ID="additionalinfo" runat="server" AppendDataBoundItems="True" 
                                                                CellPadding="0" CellSpacing="0" RepeatLayout="Flow" AutoPostBack="true"
                                                          onselectedindexchanged="additionalinfo_SelectedIndexChanged" CausesValidation="false">
                                                        
                                                         <asp:ListItem Value="256" Text="Honors Program" />
                                                         </asp:CheckBoxList>
                             <asp:Panel ID="Panel2" runat="server" Visible="false" >
                                                 
                                                
                    	                        <h3>GPA</h3>
                    	                        <!--GPA and class rank details-->
                    	                         <table style="width:95%;height:100%;border:0" width="100%">
                    	                                 <tr>
                    	                                        <td style="border:0">If weighted, check here&nbsp;<asp:CheckBox 
                                                                        ID="weightedGPA" runat="server" oncheckedchanged="weightedGPA_CheckedChanged" AutoPostBack="true" /> </td>
                    	                                 </tr>
                    	                                 <tr>
                    	                                        <td style="border:0">GPA&nbsp;
                                                                    <asp:TextBox ID="gpa" runat="server" Width="60px"></asp:TextBox>
                                                                    <asp:RequiredFieldValidator ID="required_gpa" runat="server" 
                                                                        ControlToValidate="gpa" Display="Dynamic" 
                                                                        Enabled="false"  ErrorMessage="Please enter the GPA"
                                                                        SetFocusOnError="true" ValidationGroup="Submit"></asp:RequiredFieldValidator><br />
                                                                    <asp:RangeValidator ID="validator_gpa" runat="server" ErrorMessage="Please enter a valid number for GPA" ControlToValidate="gpa" MinimumValue="0" MaximumValue="10" Type="Double" SetFocusOnError="True"></asp:RangeValidator>    
                                                                </td>
                                                           </tr>
                                                           <tr>
                                    	                        <td style="border:0"> Highest Possible GPA in your class 
                                                                    <asp:TextBox ID="classgpa" runat="server" Width="70px"></asp:TextBox>
                                                                    <asp:RequiredFieldValidator ID="required_classgpa" runat="server" Enabled="false"
                                                                        ControlToValidate="classgpa" ErrorMessage="Please enter the highest GPA in the class"
                                                                         SetFocusOnError="true" ValidationGroup="Submit"></asp:RequiredFieldValidator><br />
                                                                    <asp:RangeValidator ID="validator_classgpa" runat="server" Display="Dynamic" 
                                                                        ErrorMessage="Please enter a valid number for GPA" ControlToValidate="classgpa" 
                                                                        MinimumValue="0" MaximumValue="10" Type="Double" SetFocusOnError="True" 
                                                                        ValidationGroup="Submit"></asp:RangeValidator><br />
                                                                    <asp:CompareValidator ID="compare_gpa" runat="server" ErrorMessage="GPA should be less than or equal to class highest GPA"
                                                                     ControlToValidate="classgpa" Operator="GreaterThanEqual" Type="Double" ValidationGroup="Submit" Display="Dynamic" 
                                                                        Enabled="false" ControlToCompare="gpa" SetFocusOnError="True"></asp:CompareValidator> 
                                                                      
                    	                                        </td>
                    	                                 </tr>
                    	                                 
                    	                                 <tr>
                    	                                         <td style="border:0">Class rank&nbsp; 
                                                                    <asp:TextBox ID="classrank" runat="server" Width="50px"></asp:TextBox>
                                                                     &nbsp; of &nbsp;
                                                                    <asp:TextBox ID="totalclass" runat="server" Width="60px"></asp:TextBox>
                                                                  <asp:RequiredFieldValidator ID="required_classrank" runat="server" ErrorMessage="Please enter a valid number for class rank" 
                                                                      ControlToValidate="classrank" Enabled="false" SetFocusOnError="True" ValidationGroup="Submit" >*</asp:RequiredFieldValidator>
                                                                    <br />
                                                                    <asp:RequiredFieldValidator ID="required_totalclass" runat="server" ErrorMessage="Please enter a valid number for total class rank"
                                                                      ControlToValidate="totalclass" Enabled="false" SetFocusOnError="True" ValidationGroup="Submit" >*</asp:RequiredFieldValidator><br />
                                                                    <asp:RangeValidator ID="classrank_range" runat="server" 
                                                                         ErrorMessage="Please enter a valid number value for class rank." ControlToValidate="classrank"  
                                                                         MaximumValue="10000" MinimumValue="0" Type="Double"></asp:RangeValidator><br />
                                                                     <asp:RangeValidator ID="totalrank1_range" runat="server" ErrorMessage="Please enter a valid number value for the total rank." ControlToValidate="totalclass" 
                                                                         MaximumValue="10000" MinimumValue="0" Type="Double" ></asp:RangeValidator><br />
                                                                      <asp:CompareValidator ID="compare_rank" runat="server" ErrorMessage="Class rank has to be equal to or lower than the total class rank"
                                                                     ControlToValidate="totalclass" Operator="GreaterThanEqual" Type="Integer" ValidationGroup="Submit"
                                                                        Enabled="false" ControlToCompare="classrank" SetFocusOnError="True"></asp:CompareValidator>    
                                                                 </td>
                                                         </tr>
                                          </table>
                                          
                                          </asp:Panel>
                        </div>
                         
                        <table style="width:30%; height:100%">
                                                <tr>
                                                    <td>
                                                        <asp:Button ID="Submit" runat="server" Text="Submit Form" 
                                                            onclick="Submit1_Click"  ValidationGroup="Submit" OnClientClick="if(Page_ClientValidate()) {return Check();} else {return disable_validations();}" />
                                                   </td>
                                                    <td>
                                                        <asp:Button ID="Reset" runat="server" Text="Reset Form" 
                                                            OnClientClick="Reset1_Click" onclick="Reset_Click"/></td>
                                                 </tr>
                                            </table> 
                        
                        </form>
                    </body>
                    </html>
                    code behind for this html,
                    Code:
                    namespace WebApplication3
                    {
                        public partial class WebForm3 : System.Web.UI.Page
                        {
                            
                            protected void Page_Load(object sender, EventArgs e)
                            {
                    
                    
                            }
                    
                            protected void Submit1_Click(object sender, EventArgs e)
                            {
                    
                                if (Page.IsValid)
                                    Response.Redirect("http://www.google.com");
                    
                                else
                                {
                                    errmsg.Enabled = true;
                                    errmsg.Visible = true;
                                    errmsg.Text = "Errors";
                    
                                }
                    
                            }
                    
                            protected void additionalinfo_SelectedIndexChanged(object sender, EventArgs e)
                            {
                                if (additionalinfo.Items[0].Selected == true)
                                {
                                    Panel2.Visible = true;
                                    SetFocus(weightedGPA);
                                }
                                else
                                {
                                    Panel2.Visible = false;
                                    SetFocus(Submit);
                                }
                            }
                            protected void Reset_Click(object sender, EventArgs e)
                            {
                                Server.Transfer("WebForm3.aspx");
                            }
                    
                            protected void weightedGPA_CheckedChanged(object sender, EventArgs e)
                            {
                                if (weightedGPA.Checked == true)
                                {
                    
                                    required_gpa.Enabled = true;
                                    required_gpa.SetFocusOnError = true;
                    
                                    required_classgpa.Enabled = true;
                                    required_classgpa.SetFocusOnError = true;
                    
                                }
                                else
                                {
                                    required_gpa.Enabled = false;
                                    required_classgpa.Enabled = false;
                    
                                }
                            }
                        }
                    }
                    both these do not work. i am exhausted exploring the reasons for its failure. can somebody please let em know why this code is failing. thanks in advance.

                    Comment

                    • liawcv
                      New Member
                      • Jan 2009
                      • 33

                      #11
                      user1980 -- Hi, I run your codes (the custom validator version) and find it works with few modifications:

                      ----------

                      1. You forget to set the "ValidationGrou p" property to "Submit" for some of the validators. For this reason, certain validators are not called when you hit the submit button.

                      Solution: Set the "ValidationGrou p" property accordingly for all validators.

                      2. After I set the "ValidationGrou p" property, another problem occurs -- If "gpa" textbox has value and "classgpa" textbox has no value, the custom validator detects the error. However, if "classgpa" textbox has value and "gpa" textbox has no value, the custom validator does not detect the error.

                      Reason: This is because you set the "ControlToValid ate" property of the custom validator to "gpa". This causes the custom validator won't be called if the "gpa" textbox is empty.

                      Solution: (1) Leave the "ControlToValid ate" property of the custom validator empty. This will ensure the custom validator to be called regardless if the "gpa" textbox is empty or not.

                      OR (2) You can still set "ControlToValid ate" to "gpa". However, you should also set its "ValidateEmptyT ext" property to "True". This will ensure the custom validator to be called even if the textbox is empty.

                      ----------

                      By doing the steps above, I get the validators work. Here are somethings I would like to highlight:

                      a) Range, Compare, RegularExpressi on and Custom validators will not be called if the attached textbox is empty. For example, if you want to validate if a textbox is not empty and the value is an integer between 0 - 100, you should use 2 validators together: RequiredField and Range.

                      b) Different from others, the "ControlToValid ate" property for custom validator is optional. To ensure custom validator will check against empty text, set its "ValidateEmptyT ext" property to "True".

                      Hope these help... : )

                      Comment

                      • user1980
                        New Member
                        • Dec 2009
                        • 112

                        #12
                        thanks a lot..it works as required now..but one more small question..is there a way that we can set the focus on the text box that has no value..I mean either gpa or classgpa. I can set the property setfocusonerror to true but it would be set to gpa..but if user does not fill in the classgpa..it would still focus gpa...so is there a way that I can change it. I tried putting the focus statement in the clientvalidate function but it did not work. Infact it did not validate when I did the statement. thank you for all you help

                        Comment

                        • user1980
                          New Member
                          • Dec 2009
                          • 112

                          #13
                          hi there..I did try to put the lines
                          if(txt2.value == "")
                          document.getEle mentById("<%=cl assgpa.ClientID %>").focus();
                          and it is focusing the required text box....
                          thank you for all the help and guidance.....it really solved my problem...thank you once again

                          Comment

                          Working...