【问题标题】:validation for textbox setting dashes(-) automatically自动验证文本框设置破折号(-)
【发布时间】:2018-02-20 21:22:00
【问题描述】:

我有这个代码我试图验证它但无法所以我希望它看起来像这样12-12345-1-1 当用户在文本框中键入它应该能够自动获取破折号这可能通过 C#j-query

<asp:TextBox ID="txtNum" runat="server" placeholder="number" class="form-control" OnTextChanged="txtNum_TextChanged1" ></asp:TextBox>
<asp:RegularExpressionValidator ID="regxNum" ValidationExpression="\d{3}\d{3}\d{4}" runat="server" ErrorMessage="Invalid Num#" ControlToValidate="txtNum" ForeColor="Red"></asp:RegularExpressionValidator>

C#

if ((txtNum.Text.ToString().Length == 2) || (txtNum.Text.ToString().Length == 5) || (txtNum.Text.ToString().Length == 1))
      txtNum.Text = txtNum.Text.ToString() + "-";

【问题讨论】:

    标签: c# jquery asp.net


    【解决方案1】:

    如果您希望客户端函数添加破折号,您可以执行以下操作。

    <asp:TextBox ID="TextBox1" runat="server" MaxLength="12"></asp:TextBox>
    
    <script type="text/javascript">
        $('#<%= TextBox1.ClientID %>').keydown(function () {
            var txt = $(this).val();
            if (txt.length === 2 || txt.length === 8 || txt.length === 10) {
                $(this).val(txt += "-");
            }
        });
    </script>
    

    一个 c# 示例应该是这样的

    //source string
    string input = "12-12-3451-1";
    
    //remove wrong dashes first
    input = input.Replace("-", "");
    
    //loop all characters in the string, doing this in a loop prevents index out of range
    //exception when string it shorter that 9
    for (int i = 0; i < input.Length; i++)
    {
        //insert the appropriate dashes
        if (i == 2 || i == 8 || i == 10)
        {
            input = input.Insert(i, "-");
        }
    }
    
    //show results
    Label1.Text = input;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-05
      • 1970-01-01
      • 1970-01-01
      • 2021-04-07
      • 1970-01-01
      • 1970-01-01
      • 2020-09-19
      • 2023-04-02
      相关资源
      最近更新 更多