Before submitting the form I need to test if the sum ( txtA + txtB) is greater than 100. Is it possible to do this with a CustomValidator
, because I don't know if I can choose the 2 textbox 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.
you can do as :
<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;
}
When you drop a custom validation in your page, you can link the validator to a control, but if you want to perform multiple validations over more than one control, you need to include the following attribute
OnServerValidate="MyMethodOnServerSide"
and define that 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 asign the args.IsValid
property to the value you need. On the other hand the validation is done before you load the page, so if you clicked a button that performs an action like reading values from the DB in case everything is correct, on that action 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
is false too. Hope this helps
You need to add another control, <asp:HiddenField>
and then leverage jQuery
to set the value of that control. It might look something like this:
<asp:HiddenField ID="SumOfValues" />
<asp:CustomValidator ID="CustomValidator2"
runat="server"
ErrorMessage="CustomValidator"
ControlToValidate="SumOfValues" />
$(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 that should allow you validate that hidden control. However, one thing you'll need to make sure to do on all three controls is leverage ClientIDMode
and set it to Static
so that the names are exactly what you specify in the markup when they get to the page.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.