gpt4 book ai didi

c# - 如何基于 DropDownList 选择验证具有 RegularExpression 的 TextBox?

转载 作者:太空宇宙 更新时间:2023-11-03 13:17:36 26 4
gpt4 key购买 nike

我想使用正则表达式验证基于下拉列表的文本框。我想根据下拉列表中选择的卡类型验证信用卡号。

这是我的代码示例:

<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>

还有我的其他代码:

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;
}
}

因此,当我在下拉列表中选择 MasterCard 并在文本框中输入数字时。我想使用正则表达式 ^(5[1-5])([0-9]{14})$ 进行验证。而且当我在 Dropbox 列表中选择 Visa 并在文本框中输入数字时,它将使用 ^(4)([0-9]{15})$< 的表达式进行验证.

这里是万事达卡:

比赛:5212345678901234

不匹配:1234567890123456

最佳答案

你可以做的如下:

您需要在文本框的末尾添加一个正则表达式验证器,而不是自定义验证器 drop down list 的代码,使用 if 语句允许更改持续存在。此外,您的下拉列表 需要将Auto Post Back 设置为True 以允许更改发生。

这是您的问题背后的理想代码:

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})$";
}
}

关于c# - 如何基于 DropDownList 选择验证具有 RegularExpression 的 TextBox?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25503764/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com