473,398 Members | 2,393 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,398 software developers and data experts.

Disabling validations

112 100+
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,

Expand|Select|Wrap|Line Numbers
  1. OnClientClick="if(Page_ClientValidate()) return Check();"
my javascript

Expand|Select|Wrap|Line Numbers
  1. Function Check()
  2. {    
  3.         var Valtxtbox1 = document.getElementById("<%=txtbox1.ClientID%>").value;  
  4.             var Valtxtbox2 = document.getElementById("<%=txtbox2.ClientID%>").value;  
  5.  
  6.  
  7.             if((Valtxtbox1 != '') && (Valtxtbox2 == ''))
  8.             {
  9.  
  10.                 alert('Please enter in txtbox2');
  11.                 ValidatorEnable(document.getElementById('required_txtbox2'), true); 
  12.                 return false;
  13.             }
  14.  
  15.             if ((Valtxtbox2 != '') && (Valtxtbox1 == ''))
  16.             {
  17.                 if(parseInt(Valtxtbox2))
  18.                 {
  19.                 alert('Please enter in txtbox1');
  20.                  ValidatorEnable(document.getElementById('required_txtbox1'), true); 
  21.                 }
  22.                 else
  23.                 {
  24.                 document.getElementById("<%=txtbox1.ClientID%>").value = '';
  25.                 }
  26.                 return false;
  27.             }
  28.  
  29.            if ((Valtxtbox1 == '') && (Valtxtbox2 == ''))
  30.             {  
  31.                ValidatorEnable(document.getElementById('required_txtbox1'), false);
  32.                ValidatorEnable(document.getElementById('required_txtbox2'), false);
  33.             } 
  34.  
  35. return true;
  36.  
  37. }
  38.  
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_ClientValidate 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_ClientValidate 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..
Mar 31 '10 #1

✓ answered by liawcv

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

----------

1. You forget to set the "ValidationGroup" 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 "ValidationGroup" property accordingly for all validators.

2. After I set the "ValidationGroup" 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 "ControlToValidate" 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 "ControlToValidate" 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 "ControlToValidate" to "gpa". However, you should also set its "ValidateEmptyText" 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, RegularExpression 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 "ControlToValidate" property for custom validator is optional. To ensure custom validator will check against empty text, set its "ValidateEmptyText" property to "True".

Hope these help... : )

12 2790
Frinavale
9,735 Expert Mod 8TB
Hmm...consider the following:

Expand|Select|Wrap|Line Numbers
  1. If(TextBox1.value == ""){
  2.   alert('Please enter a value for TextBox1");
  3. }Else If(TextBox2.value ==""){
  4.   alert("Please enter a value for TextBox2");
  5. }Else{
  6.   //in this case both TextBox1 and TextBox2 have values in them
  7.   //you can do further validation on what was entered if you need to
  8.   // or you can just get rid of this case.
  9. }
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
Apr 1 '10 #2
user1980
112 100+
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.
Apr 15 '10 #3
Frinavale
9,735 Expert Mod 8TB
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
Apr 15 '10 #4
user1980
112 100+
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.
Expand|Select|Wrap|Line Numbers
  1. 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.
Apr 15 '10 #5
Frinavale
9,735 Expert Mod 8TB
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
Apr 15 '10 #6
user1980
112 100+
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.
Apr 15 '10 #7
Frinavale
9,735 Expert Mod 8TB
:) sounds like you know what you're doing :)

If you need help just ask.
Apr 15 '10 #8
liawcv
33
RequiredValidator may not suit your needs. Consider CustomValidator. Assign its "ClientValidationFunction" 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:

Expand|Select|Wrap|Line Numbers
  1. // JavaScript : Client-side validation
  2. function ClientValidate(sender, args) {
  3.     var txt1 = document.getElementById("<%= TextBox1.ClientID %>");
  4.     var txt2 = document.getElementById("<%= TextBox2.ClientID %>");
  5.     if ((txt1.value != "" && txt2.value == "") ||
  6.         (txt1.value == "" && txt2.value != "")) {
  7.         args.IsValid = false;
  8.     } else {
  9.         args.IsValid = true;
  10.     }
  11. }
Expand|Select|Wrap|Line Numbers
  1. // C# : Server-side validation
  2. protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
  3. {
  4.     if ((TextBox1.Text != "" && TextBox2.Text == "") ||
  5.         (TextBox1.Text == "" && TextBox2.Text != ""))
  6.     {
  7.         args.IsValid = false;
  8.     }
  9.     else
  10.     {
  11.         args.IsValid = true;
  12.     }
  13. }
Hope it helps. : )
Apr 16 '10 #9
user1980
112 100+
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

Expand|Select|Wrap|Line Numbers
  1. <html xmlns="http://www.w3.org/1999/xhtml" >
  2. <head id="Head1" runat="server">
  3.     <title></title>
  4.  
  5.     <script language="javascript">
  6.  
  7.         function ClientValidate(sender, args) {
  8.             var txt1 = document.getElementById("<%= gpa.ClientID %>");
  9.             var txt2 = document.getElementById("<%= classgpa.ClientID %>");
  10.             if ((txt1.value != "" && txt2.value == "") ||
  11.         (txt1.value == "" && txt2.value != "")) {
  12.                 args.IsValid = false;
  13.             } else {
  14.                 args.IsValid = true;
  15.             }
  16.         }
  17.  
  18. </head>
  19. <body>
  20.     <form id="form1" runat="server">
  21.     <div>
  22.              <asp:ValidationSummary ID="ValidationSummary1" runat="server" 
  23.                       Font-Names="Arial" Font-Size="Small" 
  24.                       HeaderText="Please correct the following errors." ShowMessageBox="true" 
  25.                       ShowSummary="false" ValidationGroup="Submit" />
  26.     <table style="width:95%; height:100%">
  27.  
  28.                                   <tr>
  29.                                      <td style="width:40%">Title:</td>
  30.                                      <td valign="top">
  31.                                        <asp:RadioButtonList ID="Sex" runat="server" AppendDataBoundItems="true" CellPadding="0" CellSpacing="0" RepeatDirection="Horizontal" RepeatLayout="Flow" class="nonbox">
  32.                                              <asp:ListItem Value="2">Mr.</asp:ListItem>
  33.                                              <asp:ListItem Value="1">Ms.</asp:ListItem>
  34.                                        </asp:RadioButtonList>
  35.                                        <asp:RequiredFieldValidator ID="RequiredFieldValidator_Sex" runat="server" 
  36.                                              ErrorMessage="Please select a title" Display="Dynamic" 
  37.                                              ControlToValidate="Sex" SetFocusOnError="True" ValidationGroup="Submit">*</asp:RequiredFieldValidator>
  38.                                      </td>
  39.                                   </tr>
  40.  
  41.                                   <tr>
  42.                                     <td >First Name:</td>
  43.                                     <td><asp:TextBox ID="first" runat="server" Width="225px"></asp:TextBox>
  44.                                         <asp:RequiredFieldValidator ID="RequiredFieldValidator_first" runat="server" ErrorMessage="Please enter your first name" 
  45.                                               ControlToValidate="first"  Display="Dynamic" SetFocusOnError="True" 
  46.                                             ValidationGroup="Submit">*</asp:RequiredFieldValidator>
  47.                                      </td>
  48.                                   </tr>
  49.                                   </table>
  50.  
  51.     <asp:Label ID="errmsg" runat="server" Text="" Visible="false" Enabled="false" Font-Bold="true" ForeColor="Red"></asp:Label>
  52.     <h3>Additional Information</h3>
  53.  
  54.                                      <asp:CheckBoxList ID="additionalinfo" runat="server" AppendDataBoundItems="True" 
  55.                                             CellPadding="0" CellSpacing="0" RepeatLayout="Flow" AutoPostBack="true"
  56.                                       onselectedindexchanged="additionalinfo_SelectedIndexChanged" CausesValidation="false">
  57.  
  58.                                      <asp:ListItem Value="256" Text="Honors Program" />
  59.                                      </asp:CheckBoxList>
  60.          <asp:Panel ID="Panel2" runat="server" Visible="false" >
  61.  
  62.  
  63.                             <h3>GPA</h3>
  64.                             <!--GPA and class rank details-->
  65.                              <table style="width:95%;height:100%;border:0" width="100%">
  66.                                      <tr>
  67.                                             <td style="border:0">If weighted, check here&nbsp;<asp:CheckBox 
  68.                                                     ID="weightedGPA" runat="server" oncheckedchanged="weightedGPA_CheckedChanged" AutoPostBack="true" /> </td>
  69.                                      </tr>
  70.                                      <tr>
  71.                                             <td style="border:0">GPA&nbsp;
  72.                                                 <asp:TextBox ID="gpa" runat="server" Width="60px"></asp:TextBox>
  73.                                                <%-- <asp:RequiredFieldValidator ID="required_gpa" runat="server" 
  74.                                                     ControlToValidate="gpa" Display="Dynamic" 
  75.                                                     Enabled="false"  ErrorMessage="Please enter the GPA"
  76.                                                     SetFocusOnError="true" ValidationGroup="Submit"></asp:RequiredFieldValidator>--%><br />
  77.                                                 <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>    
  78.                                                 <asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="gpa" 
  79.                                                     ErrorMessage="Please enter the GPA and the highest GPA" 
  80.                                                     ClientValidationFunction="ClientValidate" 
  81.                                                     onservervalidate="CustomValidator1_ServerValidate"></asp:CustomValidator>   
  82.                                             </td>
  83.                                        </tr>
  84.                                        <tr>
  85.                                             <td style="border:0"> Highest Possible GPA in your class 
  86.                                                 <asp:TextBox ID="classgpa" runat="server" Width="70px"></asp:TextBox>
  87.                                                 <%--<asp:RequiredFieldValidator ID="required_classgpa" runat="server" Enabled="false"
  88.                                                     ControlToValidate="classgpa" ErrorMessage="Please enter the highest GPA in the class"
  89.                                                      SetFocusOnError="true" ValidationGroup="Submit"></asp:RequiredFieldValidator>--%><br />
  90.                                                 <asp:RangeValidator ID="validator_classgpa" runat="server" Display="Dynamic" 
  91.                                                     ErrorMessage="Please enter a valid number for GPA" ControlToValidate="classgpa" 
  92.                                                     MinimumValue="0" MaximumValue="10" Type="Double" SetFocusOnError="True" 
  93.                                                     ValidationGroup="Submit"></asp:RangeValidator><br />
  94.                                                 <asp:CompareValidator ID="compare_gpa" runat="server" ErrorMessage="GPA should be less than or equal to class highest GPA"
  95.                                                  ControlToValidate="classgpa" Operator="GreaterThanEqual" Type="Double" ValidationGroup="Submit" Display="Dynamic" 
  96.                                                     Enabled="false" ControlToCompare="gpa" SetFocusOnError="True"></asp:CompareValidator> 
  97.  
  98.                                             </td>
  99.                                      </tr>
  100.  
  101.                                      <tr>
  102.                                              <td style="border:0">Class rank&nbsp; 
  103.                                                 <asp:TextBox ID="classrank" runat="server" Width="50px"></asp:TextBox>
  104.                                                  &nbsp; of &nbsp;
  105.                                                 <asp:TextBox ID="totalclass" runat="server" Width="60px"></asp:TextBox>
  106.                                               <asp:RequiredFieldValidator ID="required_classrank" runat="server" ErrorMessage="Please enter a valid number for class rank" 
  107.                                                   ControlToValidate="classrank" Enabled="false" SetFocusOnError="True" ValidationGroup="Submit" >*</asp:RequiredFieldValidator>
  108.                                                 <br />
  109.                                                 <asp:RequiredFieldValidator ID="required_totalclass" runat="server" ErrorMessage="Please enter a valid number for total class rank"
  110.                                                   ControlToValidate="totalclass" Enabled="false" SetFocusOnError="True" ValidationGroup="Submit" >*</asp:RequiredFieldValidator><br />
  111.                                                 <asp:RangeValidator ID="classrank_range" runat="server" 
  112.                                                      ErrorMessage="Please enter a valid number value for class rank." ControlToValidate="classrank"  
  113.                                                      MaximumValue="10000" MinimumValue="0" Type="Double"></asp:RangeValidator><br />
  114.                                                  <asp:RangeValidator ID="totalrank1_range" runat="server" ErrorMessage="Please enter a valid number value for the total rank." ControlToValidate="totalclass" 
  115.                                                      MaximumValue="10000" MinimumValue="0" Type="Double" ></asp:RangeValidator><br />
  116.                                                   <asp:CompareValidator ID="compare_rank" runat="server" ErrorMessage="Class rank has to be equal to or lower than the total class rank"
  117.                                                  ControlToValidate="totalclass" Operator="GreaterThanEqual" Type="Integer" ValidationGroup="Submit"
  118.                                                     Enabled="false" ControlToCompare="classrank" SetFocusOnError="True"></asp:CompareValidator>    
  119.                                              </td>
  120.                                      </tr>
  121.                       </table>
  122.  
  123.                       </asp:Panel>
  124.     </div>
  125.  
  126.     <table style="width:30%; height:100%">
  127.                             <tr>
  128.                                 <td>
  129.                                     <asp:Button ID="Submit" runat="server" Text="Submit Form" 
  130.                                         onclick="Submit1_Click"  ValidationGroup="Submit" />
  131.                                </td>
  132.                                 <td>
  133.                                     <asp:Button ID="Reset" runat="server" Text="Reset Form" 
  134.                                         OnClientClick="Reset1_Click" onclick="Reset_Click"/></td>
  135.                              </tr>
  136.                         </table> 
  137.  
  138.     </form>
  139. </body>
  140. </html>
  141.  
  142.  
my code behind page,

Expand|Select|Wrap|Line Numbers
  1. namespace WebApplication3
  2. {
  3.     public partial class WebForm4 : System.Web.UI.Page
  4.     {
  5.          protected void Page_Load(object sender, EventArgs e)
  6.         {
  7.  
  8.  
  9.         }
  10.  
  11.         protected void Submit1_Click(object sender, EventArgs e)
  12.         {
  13.  
  14.             if (Page.IsValid)
  15.                 Response.Redirect("http://www.google.com");
  16.  
  17.             else
  18.             {
  19.                 errmsg.Enabled = true;
  20.                 errmsg.Visible = true;
  21.                 errmsg.Text = "Errors";
  22.  
  23.             }
  24.  
  25.         }
  26.  
  27.         protected void additionalinfo_SelectedIndexChanged(object sender, EventArgs e)
  28.         {
  29.             if (additionalinfo.Items[0].Selected == true)
  30.             {
  31.                 Panel2.Visible = true;
  32.                 SetFocus(weightedGPA);
  33.             }
  34.             else
  35.             {
  36.                 Panel2.Visible = false;
  37.                 SetFocus(Submit);
  38.             }
  39.         }
  40.         protected void Reset_Click(object sender, EventArgs e)
  41.         {
  42.             Server.Transfer("WebForm3.aspx");
  43.         }
  44.  
  45.         protected void weightedGPA_CheckedChanged(object sender, EventArgs e)
  46.         {
  47.             //if (weightedGPA.Checked == true)
  48.             //{
  49.  
  50.             //    required_gpa.Enabled = true;
  51.             //    required_gpa.SetFocusOnError = true;
  52.  
  53.             //    required_classgpa.Enabled = true;
  54.             //    required_classgpa.SetFocusOnError = true;
  55.  
  56.             //}
  57.             //else
  58.             //{
  59.             //    required_gpa.Enabled = false;
  60.             //    required_classgpa.Enabled = false;
  61.  
  62.             //}
  63.         }
  64.  
  65.         protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
  66.         {
  67.             if ((gpa.Text != "" && classgpa.Text == "") ||
  68.         (gpa.Text == "" && classgpa.Text != ""))
  69.             {
  70.                 args.IsValid = false;
  71.             }
  72.             else
  73.             {
  74.                 args.IsValid = true;
  75.             }
  76.         }
  77.     }
  78.     }
  79.  
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.

Expand|Select|Wrap|Line Numbers
  1. <html xmlns="http://www.w3.org/1999/xhtml" >
  2. <head runat="server">
  3.     <title></title>
  4.  
  5.     <script>
  6.  
  7.         function Check() {
  8.             alert("checking");
  9.  
  10.             // GPA and highest GPA in the class
  11.             var Valgpa = document.getElementById("<%=gpa.ClientID%>").value;
  12.             var Valclassgpa = document.getElementById("<%=classgpa.ClientID%>").value;
  13.  
  14.  
  15.             if ((Valgpa != '') && (Valclassgpa == '')) {
  16.              //   alert("1");
  17.                 if (parseFloat(Valgpa)) {
  18.                //     alert("2");
  19.                     alert('Please enter the highest GPA in class');
  20.                     ValidatorEnable(document.getElementById('required_classgpa'), true);
  21.                     document.form2.classgpa.focus();
  22.                 }
  23.                 else {
  24.                     document.getElementById("<%=gpa.ClientID%>").value = '';
  25.                 }
  26.                 return false;
  27.             }
  28.  
  29.             if ((Valclassgpa != '') && (Valgpa == '')) {
  30.                 if (parseFloat(Valclassgpa)) {
  31.                     alert('Please enter the GPA');
  32.                     ValidatorEnable(document.getElementById('required_gpa'), true);
  33.                     document.form2.gpa.focus();
  34.                 }
  35.                 else {
  36.                     document.getElementById("<%=classgpa.ClientID%>").value = '';
  37.                 }
  38.                 return false;
  39.             }
  40.  
  41.             if ((Valgpa != '') && (Valclassgpa != '')) {
  42.                 if (parseFloat(Valgpa) && parseFloat(Valclassgpa)) {
  43.                     if (Valgpa > Valclassgpa) {
  44.                         alert('GPA should be less than or equal to class highest GPA');
  45.                         document.form2.classgpa.focus();
  46.                         ValidatorEnable(document.getElementById('compare_gpa'), true);
  47.                         return false;
  48.                     }
  49.                 }
  50.             }
  51.  
  52.             if ((Valgpa == '') && (Valclassgpa == '')) {
  53.                 ValidatorEnable(document.getElementById('required_classgpa'), false);
  54.                 ValidatorEnable(document.getElementById('required_gpa'), false);
  55.  
  56.             }
  57.  
  58.  
  59.             //Class rank and total rank
  60.             var Valrank = document.getElementById("<%=classrank.ClientID%>").value;
  61.             var Valtotalclass = document.getElementById("<%=totalclass.ClientID%>").value;
  62.  
  63.             if ((Valrank != '') && (Valtotalclass == '')) {
  64.                 alert('ges here');
  65.                 if (parseInt(Valrank)) {
  66.                     alert('Please enter a valid number for total class rank');
  67.                     ValidatorEnable(document.getElementById('required_totalclass'), true);
  68.                     document.form2.totalclass.focus();
  69.                 }
  70.                 else {
  71.                     document.getElementById("<%=classrank.ClientID%>").value = '';
  72.                 }
  73.                 return false;
  74.             }
  75.  
  76.             if ((Valtotalclass != '') && (Valrank == '')) {
  77.                 if (parseInt(Valtotalclass)) {
  78.                     alert('Please enter a valid number for class rank');
  79.                     ValidatorEnable(document.getElementById('required_classrank'), true);
  80.                     document.form2.classrank.focus();
  81.                 }
  82.                 else {
  83.                     document.getElementById("<%=totalclass.ClientID%>").value = '';
  84.                 }
  85.                 return false;
  86.             }
  87.             if ((Valrank != '') && (Valtotalclass != '')) {
  88.                 if (parseInt(Valrank) && parseInt(Valtotalclass)) {
  89.                     if (Valrank > Valtotalclass) {
  90.                         alert('Class rank has to be equal to or lower than the total class rank');
  91.                         ValidatorEnable(document.getElementById('compare_rank'), true);
  92.                         document.form2.classrank.focus();
  93.                         return false;
  94.                     }
  95.                 }
  96.             }
  97.  
  98.             if ((Valrank == '') && (Valtotalclass == '')) {
  99.                 ValidatorEnable(document.getElementById('required_totalclass'), false);
  100.                 ValidatorEnable(document.getElementById('required_classrank'), false);
  101.             }
  102.             return true;
  103.         }
  104.  
  105.  
  106.  
  107.         function disable_validations() {
  108.             alert("disable");
  109.  
  110.             var Valgpa = document.getElementById("<%=gpa.ClientID%>").value;
  111.             var Valclassgpa = document.getElementById("<%=classgpa.ClientID%>").value;
  112.  
  113.             if ((Valgpa == '') && (Valclassgpa == '')) {
  114.                 alert("1");
  115.                 ValidatorEnable(document.getElementById('required_classgpa'), false);
  116.                 ValidatorEnable(document.getElementById('required_gpa'), false);
  117.             }
  118.             else {
  119.                 if ((Valgpa != '') && (Valclassgpa == '')) {
  120.                     ValidatorEnable(document.getElementById('required_classgpa'), true);
  121.                     alert('Please enter the highest GPA in class');
  122.                 }
  123.                 if ((Valgpa == '') && (Valclassgpa != '')) {
  124.                     ValidatorEnable(document.getElementById('required_gpa'), true);
  125.                     alert('Please enter the GPA');
  126.                 }
  127.                 //  return false;
  128.  
  129.             }
  130.  
  131.  
  132.             var Valrank = document.getElementById("<%=classrank.ClientID%>").value;
  133.             var Valtotalclass = document.getElementById("<%=totalclass.ClientID%>").value;
  134.  
  135.  
  136.             if ((Valrank == '') && (Valtotalclass == '')) {
  137.                 alert("2");
  138.                 ValidatorEnable(document.getElementById('required_totalclass'), false);
  139.                 ValidatorEnable(document.getElementById('required_classrank'), false);
  140.             }
  141.             else {
  142.                 if ((Valrank != '') && (Valtotalclass == '')) {
  143.                     ValidatorEnable(document.getElementById('required_totalclass'), true);
  144.                     alert('Please enter a valid number for class rank');
  145.                 }
  146.                 if ((Valrank == '') && (Valtotalclass != '')) {
  147.                     ValidatorEnable(document.getElementById('required_classrank'), true);
  148.                     alert('Please enter a valid number for total class rank');
  149.                 }
  150.                 //     return false;
  151.             }
  152.             return true;
  153.         }
  154.     </script>
  155. </head>
  156. <body>
  157.     <form id="form1" runat="server">
  158.     <div>
  159.              <asp:ValidationSummary ID="ValidationSummary1" runat="server" 
  160.                       Font-Names="Arial" Font-Size="Small" 
  161.                       HeaderText="Please correct the following errors." ShowMessageBox="true" 
  162.                       ShowSummary="false" ValidationGroup="Submit" />
  163.     <table style="width:95%; height:100%">
  164.  
  165.                                   <tr>
  166.                                      <td style="width:40%">Title:</td>
  167.                                      <td valign="top">
  168.                                        <asp:RadioButtonList ID="Sex" runat="server" AppendDataBoundItems="true" CellPadding="0" CellSpacing="0" RepeatDirection="Horizontal" RepeatLayout="Flow" class="nonbox">
  169.                                              <asp:ListItem Value="2">Mr.</asp:ListItem>
  170.                                              <asp:ListItem Value="1">Ms.</asp:ListItem>
  171.                                        </asp:RadioButtonList>
  172.                                        <asp:RequiredFieldValidator ID="RequiredFieldValidator_Sex" runat="server" 
  173.                                              ErrorMessage="Please select a title" Display="Dynamic" 
  174.                                              ControlToValidate="Sex" SetFocusOnError="True" ValidationGroup="Submit">*</asp:RequiredFieldValidator>
  175.                                      </td>
  176.                                   </tr>
  177.  
  178.                                   <tr>
  179.                                     <td >First Name:</td>
  180.                                     <td><asp:TextBox ID="first" runat="server" Width="225px"></asp:TextBox>
  181.                                         <asp:RequiredFieldValidator ID="RequiredFieldValidator_first" runat="server" ErrorMessage="Please enter your first name" 
  182.                                               ControlToValidate="first"  Display="Dynamic" SetFocusOnError="True" 
  183.                                             ValidationGroup="Submit">*</asp:RequiredFieldValidator>
  184.                                      </td>
  185.                                   </tr>
  186.                                   </table>
  187.  
  188.     <asp:Label ID="errmsg" runat="server" Text="" Visible="false" Enabled="false" Font-Bold="true" ForeColor="Red"></asp:Label>
  189.     <h3>Additional Information</h3>
  190.  
  191.                                      <asp:CheckBoxList ID="additionalinfo" runat="server" AppendDataBoundItems="True" 
  192.                                             CellPadding="0" CellSpacing="0" RepeatLayout="Flow" AutoPostBack="true"
  193.                                       onselectedindexchanged="additionalinfo_SelectedIndexChanged" CausesValidation="false">
  194.  
  195.                                      <asp:ListItem Value="256" Text="Honors Program" />
  196.                                      </asp:CheckBoxList>
  197.          <asp:Panel ID="Panel2" runat="server" Visible="false" >
  198.  
  199.  
  200.                             <h3>GPA</h3>
  201.                             <!--GPA and class rank details-->
  202.                              <table style="width:95%;height:100%;border:0" width="100%">
  203.                                      <tr>
  204.                                             <td style="border:0">If weighted, check here&nbsp;<asp:CheckBox 
  205.                                                     ID="weightedGPA" runat="server" oncheckedchanged="weightedGPA_CheckedChanged" AutoPostBack="true" /> </td>
  206.                                      </tr>
  207.                                      <tr>
  208.                                             <td style="border:0">GPA&nbsp;
  209.                                                 <asp:TextBox ID="gpa" runat="server" Width="60px"></asp:TextBox>
  210.                                                 <asp:RequiredFieldValidator ID="required_gpa" runat="server" 
  211.                                                     ControlToValidate="gpa" Display="Dynamic" 
  212.                                                     Enabled="false"  ErrorMessage="Please enter the GPA"
  213.                                                     SetFocusOnError="true" ValidationGroup="Submit"></asp:RequiredFieldValidator><br />
  214.                                                 <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>    
  215.                                             </td>
  216.                                        </tr>
  217.                                        <tr>
  218.                                             <td style="border:0"> Highest Possible GPA in your class 
  219.                                                 <asp:TextBox ID="classgpa" runat="server" Width="70px"></asp:TextBox>
  220.                                                 <asp:RequiredFieldValidator ID="required_classgpa" runat="server" Enabled="false"
  221.                                                     ControlToValidate="classgpa" ErrorMessage="Please enter the highest GPA in the class"
  222.                                                      SetFocusOnError="true" ValidationGroup="Submit"></asp:RequiredFieldValidator><br />
  223.                                                 <asp:RangeValidator ID="validator_classgpa" runat="server" Display="Dynamic" 
  224.                                                     ErrorMessage="Please enter a valid number for GPA" ControlToValidate="classgpa" 
  225.                                                     MinimumValue="0" MaximumValue="10" Type="Double" SetFocusOnError="True" 
  226.                                                     ValidationGroup="Submit"></asp:RangeValidator><br />
  227.                                                 <asp:CompareValidator ID="compare_gpa" runat="server" ErrorMessage="GPA should be less than or equal to class highest GPA"
  228.                                                  ControlToValidate="classgpa" Operator="GreaterThanEqual" Type="Double" ValidationGroup="Submit" Display="Dynamic" 
  229.                                                     Enabled="false" ControlToCompare="gpa" SetFocusOnError="True"></asp:CompareValidator> 
  230.  
  231.                                             </td>
  232.                                      </tr>
  233.  
  234.                                      <tr>
  235.                                              <td style="border:0">Class rank&nbsp; 
  236.                                                 <asp:TextBox ID="classrank" runat="server" Width="50px"></asp:TextBox>
  237.                                                  &nbsp; of &nbsp;
  238.                                                 <asp:TextBox ID="totalclass" runat="server" Width="60px"></asp:TextBox>
  239.                                               <asp:RequiredFieldValidator ID="required_classrank" runat="server" ErrorMessage="Please enter a valid number for class rank" 
  240.                                                   ControlToValidate="classrank" Enabled="false" SetFocusOnError="True" ValidationGroup="Submit" >*</asp:RequiredFieldValidator>
  241.                                                 <br />
  242.                                                 <asp:RequiredFieldValidator ID="required_totalclass" runat="server" ErrorMessage="Please enter a valid number for total class rank"
  243.                                                   ControlToValidate="totalclass" Enabled="false" SetFocusOnError="True" ValidationGroup="Submit" >*</asp:RequiredFieldValidator><br />
  244.                                                 <asp:RangeValidator ID="classrank_range" runat="server" 
  245.                                                      ErrorMessage="Please enter a valid number value for class rank." ControlToValidate="classrank"  
  246.                                                      MaximumValue="10000" MinimumValue="0" Type="Double"></asp:RangeValidator><br />
  247.                                                  <asp:RangeValidator ID="totalrank1_range" runat="server" ErrorMessage="Please enter a valid number value for the total rank." ControlToValidate="totalclass" 
  248.                                                      MaximumValue="10000" MinimumValue="0" Type="Double" ></asp:RangeValidator><br />
  249.                                                   <asp:CompareValidator ID="compare_rank" runat="server" ErrorMessage="Class rank has to be equal to or lower than the total class rank"
  250.                                                  ControlToValidate="totalclass" Operator="GreaterThanEqual" Type="Integer" ValidationGroup="Submit"
  251.                                                     Enabled="false" ControlToCompare="classrank" SetFocusOnError="True"></asp:CompareValidator>    
  252.                                              </td>
  253.                                      </tr>
  254.                       </table>
  255.  
  256.                       </asp:Panel>
  257.     </div>
  258.  
  259.     <table style="width:30%; height:100%">
  260.                             <tr>
  261.                                 <td>
  262.                                     <asp:Button ID="Submit" runat="server" Text="Submit Form" 
  263.                                         onclick="Submit1_Click"  ValidationGroup="Submit" OnClientClick="if(Page_ClientValidate()) {return Check();} else {return disable_validations();}" />
  264.                                </td>
  265.                                 <td>
  266.                                     <asp:Button ID="Reset" runat="server" Text="Reset Form" 
  267.                                         OnClientClick="Reset1_Click" onclick="Reset_Click"/></td>
  268.                              </tr>
  269.                         </table> 
  270.  
  271.     </form>
  272. </body>
  273. </html>
code behind for this html,
Expand|Select|Wrap|Line Numbers
  1. namespace WebApplication3
  2. {
  3.     public partial class WebForm3 : System.Web.UI.Page
  4.     {
  5.  
  6.         protected void Page_Load(object sender, EventArgs e)
  7.         {
  8.  
  9.  
  10.         }
  11.  
  12.         protected void Submit1_Click(object sender, EventArgs e)
  13.         {
  14.  
  15.             if (Page.IsValid)
  16.                 Response.Redirect("http://www.google.com");
  17.  
  18.             else
  19.             {
  20.                 errmsg.Enabled = true;
  21.                 errmsg.Visible = true;
  22.                 errmsg.Text = "Errors";
  23.  
  24.             }
  25.  
  26.         }
  27.  
  28.         protected void additionalinfo_SelectedIndexChanged(object sender, EventArgs e)
  29.         {
  30.             if (additionalinfo.Items[0].Selected == true)
  31.             {
  32.                 Panel2.Visible = true;
  33.                 SetFocus(weightedGPA);
  34.             }
  35.             else
  36.             {
  37.                 Panel2.Visible = false;
  38.                 SetFocus(Submit);
  39.             }
  40.         }
  41.         protected void Reset_Click(object sender, EventArgs e)
  42.         {
  43.             Server.Transfer("WebForm3.aspx");
  44.         }
  45.  
  46.         protected void weightedGPA_CheckedChanged(object sender, EventArgs e)
  47.         {
  48.             if (weightedGPA.Checked == true)
  49.             {
  50.  
  51.                 required_gpa.Enabled = true;
  52.                 required_gpa.SetFocusOnError = true;
  53.  
  54.                 required_classgpa.Enabled = true;
  55.                 required_classgpa.SetFocusOnError = true;
  56.  
  57.             }
  58.             else
  59.             {
  60.                 required_gpa.Enabled = false;
  61.                 required_classgpa.Enabled = false;
  62.  
  63.             }
  64.         }
  65.     }
  66. }
  67.  
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.
Apr 16 '10 #10
liawcv
33
user1980 -- Hi, I run your codes (the custom validator version) and find it works with few modifications:

----------

1. You forget to set the "ValidationGroup" 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 "ValidationGroup" property accordingly for all validators.

2. After I set the "ValidationGroup" 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 "ControlToValidate" 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 "ControlToValidate" 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 "ControlToValidate" to "gpa". However, you should also set its "ValidateEmptyText" 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, RegularExpression 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 "ControlToValidate" property for custom validator is optional. To ensure custom validator will check against empty text, set its "ValidateEmptyText" property to "True".

Hope these help... : )
Apr 17 '10 #11
user1980
112 100+
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
Apr 19 '10 #12
user1980
112 100+
hi there..I did try to put the lines
if(txt2.value == "")
document.getElementById("<%=classgpa.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
Apr 19 '10 #13

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: Naresh Agarwal | last post by:
Hi I'm using SAX Parser of Xerces Java v2.4.0 for XML Parsing. I want to perform schema validations on the xml. The problem is that root element of XML document does not have...
0
by: babash | last post by:
I designed a site with asp.net all pages are working properly on my local computer but when I upload the sit on the server on those pages that I have field validation, Buttons doesn’t work. When...
19
by: Gérard Talbot | last post by:
posted to: alt.html and comp.infosystems.www.authoring.html followup-to: comp.infosystems.www.authoring.html Hello all, I have 2 questions about validations. 1- What's basically the...
1
by: anil kumar via .NET 247 | last post by:
(Type your message here) hi, i am using save & cancel webform buttons in my webpage to withsome validations , when i am trying to save my content it issaved that time i need a popup msg like ur...
3
by: PB | last post by:
What is the rationalle for disabling JavaScript. AFAIK, the primary reason is for "security purposes" - but what specific kind of threats does the protect against? AND - is the disabling of...
12
by: Nalaka | last post by:
Hi, I suddenly started getting a lot of errors from html validation (some CSS) so I followed the following instructions to disable it. If you'd rather not have these types of HTML validation...
1
by: Anup | last post by:
In my form I and doing validations using 'Javascript' as I m using ASP1.1 and there is very less support for Validators there. //Code Behind private void Page_Load(object sender,...
0
by: luckymodiba | last post by:
How do i create or recompile the struts tld to include the autocomplete="off" function? when i try to use it like you would in html jboss gives an error, and when i remove the text from <html:text>...
2
by: prakashsurya | last post by:
Hello I am going through the validations in a form I would like to know the validations to be considered in writing javascript for email id so would u plz help me in writing the necessary...
2
by: swethak | last post by:
hi , i write the code in .htm file. It is in cgi-bin/searches/one.htm.In that i write a form submitting and validations.But validations are not worked in that .htm file. I used the same code in my...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.