Reputation: 23
I would like validate a Textbox based on a Dropdown List with regular expression. I would like to validate a credit card number based on the card type selected by the dropdown list.
Here is a sample of my code:
<table runat="server">
<tr>
<td><asp:Label ID="Label4" runat="server" Text="Credit Card Type"></asp:Label></td>
<td><asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem Text="Visa" Value="Visa"></asp:ListItem>
<asp:ListItem Text="MasterCard" Value="Mastercard"></asp:ListItem>
</asp:DropDownList></td>
</tr>
<tr>
<td><asp:Label ID="Label1" runat="server" Text="Card Number"></asp:Label></td>
<td><asp:TextBox ID="TextBox1" runat="server"></asp:TextBox></td>
<td><asp:CustomValidator ID=CustomValidator1 runat="server" ErrorMessage="Incorrect card, please re-renter!" ControlToValidate="TextBox1" Display="Dynamic" ForeColor="Red" OnServerValidate="CustomValidator1_ServerValidate"></asp:CustomValidator></td>
</tr>
<tr>
<td><asp:Button ID="Button1" runat="server" Text="Submit" CommandName="Submit"/></td>
</tr>
</table>
And my other code:
protected void CustomValidation1_ServerValidate(object Source, ServerValidateEventArgs args)
{
string expression = "";
switch (DropDownList.SelectedValue)
{
case "Visa":
expression = "^(4)([0-9]{15})$";
break;
case "MasterCard":
expression = "^(5[1-5])([0-9]{14})$";
break;
}
}
So when I select on MasterCard
on the Dropdown List and input numbers in the textbox. I would like to be validate with the regular expression ^(5[1-5])([0-9]{14})$
. And also when I select Visa
on the Dropbox List and input numbers in the textbox, it will validate with the expression of ^(4)([0-9]{15})$
.
Here it would be for MasterCard:
Matches:
5212345678901234
Does not Match:
1234567890123456
Upvotes: 2
Views: 1657
Reputation: 86
What you can do would be as follows:
Instead of a custom validator
, you will need to add a regular expression validator
at the end of the textbox
and with the process of code behind for your drop down list
, use if statements that will allow the change to persist. Also your drop down list
needs to perform Auto Post Back
setting to True
to allow the changes to occur.
Here is the ideal code behind for your question:
protected void DropDownList1_OnIndexChanged(object Source, EventArgs args)
{
if (DropDownList.SelectedItem.Text == "Visa")
{
RegularExpression1.ValidationExpression = "^(4)([0-9]{15})$";
else
RegularExpression1.ValidationExpression = "^(5[1-5])([0-9]{14})$";
}
}
Upvotes: 1
Reputation: 2169
I would do it so:
Declare 2 RegExpValidators one for VISA-Regex, another for MasterCard-Regex.
Declare OnSelectedIndexChanged
-Method for the DropDownList
in code behind.
In this method enable the correct validator based on the SelectedValue
of the DropDownList
and disable the onother one.
Upvotes: 0