Confirm two controls (CustomValidator)

Before submitting the form, I need to check if the amount exceeds (txtA + txtB) 100. Is it possible to do this using CustomValidator , because I don’t know if I can select 2 text fields in ControlToValidate

 <asp:TextBox ID="txtA" runat="server"></asp:TextBox> <asp:TextBox ID="txtB" runat="server"></asp:TextBox> <asp:CustomValidator ID="CustomValidator2" runat="server" ErrorMessage="CustomValidator" /> <asp:Button ID="Button1" runat="server" Text="Button" /> 

Thanks.

+4
source share
3 answers

you can do this:

 <asp:TextBox ID="txtA" runat="server" /> <asp:TextBox ID="txtB" runat="server" /> <asp:CustomValidator ID="CV1"runat="server" OnServerValidate="ServerValidation" ErrorMessage="Sum is less than 100" /> 

codebehind:

 protected void ServerValidation(object source, ServerValidateEventArgs args) { args.IsValid = int.Parse(txtA.Text)+ int.Parse(txtB.Text) >100; } 
+9
source

When you delete a custom check on your page, you can associate the validator with the control, but if you want to perform multiple checks on more than one control, you need to include the following attribute

  OnServerValidate="MyMethodOnServerSide" 

and define this method on the server side

 protected void MyMethodOnServerSide(object source, ServerValidateEventArgs args) { if (string.IsNullOrEmpty(mytxt1.Text) && string.IsNullOrEmpty(mytxt2.Text)) { args.IsValid = false; return; } args.IsValid = true; } 

just set the args.IsValid property args.IsValid value you need. On the other hand, the check is performed before you load the page, so if you clicked on a button that performs an action such as reading values ​​from the database, if everything is correct, in this step you need to include the following check.

 protected void cmdSearch_Click(object sender, EventArgs e) { if (Page.IsValid) { LoadDataFromDB(); } } 

When args.IsValid is false, then Page.IsValid also false. Hope this helps

+1
source

You need to add another <asp:HiddenField> and then use jQuery to set the value of this control. It might look something like this:

MARKUP

 <asp:HiddenField ID="SumOfValues" /> <asp:CustomValidator ID="CustomValidator2" runat="server" ErrorMessage="CustomValidator" ControlToValidate="SumOfValues" /> 

JQuery

 $(document).ready(function() { $('#txtA').change(sumValues); $('#txtB').change(sumValues); }); function sumValues() { var val1 = $('txtA').value(); if (val1 === undefined) { val1 = 0; } var val2 = $('txtB').value(); if (val2 === undefined) { val2 = 0; } $('#SumOfValues').value(val1 + val2); } 

and this should allow you to check out this hidden control. However, one thing you will need to do for all three controls is to use ClientIDMode and set it to Static so that the names are exactly what you specify in the markup when they get to the page.

-1
source

All Articles