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

标签 c# asp.net regex validation textbox

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

这是我的代码示例:

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

相关文章:

c# - 从 JSON 反序列化大量属性

c# - 从 pid 获取窗口标题

c# - 为什么修改一个 session 变量也会修改另一个 session 变量?

Java:使用正则表达式解析dxf文件

regex - 带有正则表达式的 debezium 表白名单

C# 数据库错误,从另一个列表框更改列表框中的项目

c# - MahApps Metro HamburgerMenu 绑定(bind)不工作

c# - 在 asp.net 中使用 OnInit 事件

asp.net - 阻止 Visual Studio 2010 启动 ASP.net 开发服务器

php - 奇怪的 PHP 字符串错误