Reputation: 21238
I'm working on an application with two input fields that's validated in different ways with RequiredFieldValidator, RangeValidator and so on. I need one more validation and that is to check that the number the user writes in input1 isn't bigger than in input2, and here's the question.
Is it possible to use validation controls to compare 2 input fields, or do I need to write code for it? I'm using a ValidationSummary control and of course I want to show all the errors with this. If it isn't possible to use validation controls to compare 2 input fields and I need to write code for this, is it possible to show the error message with the ValidationSummary anyway, and in that case how?
Thanks in advance!
Upvotes: 3
Views: 7837
Reputation: 6106
bool isLonger(string s1, string s2)
{
return s1.Length > s2.Length ? true : false;
}
returns true if the length if s1 is greater than the length of s2
Upvotes: 0
Reputation: 3084
Have you tried using the CompareValidator?
This allows you to compare 2 input fields and is a standard control as per the Requiredfield and Range validators.
<asp:CompareValidator ControlToCompare="text1" ControlToValidate="text2" ErrorMessage="error" runat="server" Operator="LessThan" Type="Integer" />
Upvotes: 1
Reputation: 5596
Use a custom validator control and use the ServerValidate event to return true/false depending on if the check is correct.
The validation summary will pick up that the Page is not valid and display your message.
C#
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
if (TextBox1.Text.Length > TextBox2.Text.Length)
args.IsValid = false;
else
args.IsValid = true;
}
.aspx
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:ValidationSummary ID="ValidationSummary1" runat="server" />
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Invalid Length" Display="None" onservervalidate="CustomValidator1_ServerValidate"></asp:CustomValidator>
<br />
<asp:Button ID="Button1" runat="server" Text="Button" />
Upvotes: 1