【问题标题】:How to not allow user to input numbers in textbox如何不允许用户在文本框中输入数字
【发布时间】:2017-03-03 15:23:03
【问题描述】:

我正在尝试制作一个不允许输入数字的文本框

我尝试了一些代码但不起作用

这是我尝试过的:

<asp:RegularExpressionValidator runat="server" ID="txtSurnameValidation" 
     ControlToValidate="txtSurname" ValidationExpression="[a-zA-Z ]*$" Display="Dynamic">
</asp:RegularExpressionValidator>

【问题讨论】:

标签: c# asp.net validation textbox


【解决方案1】:

它可以工作,但它没有显示任何消息,因为您没有设置任何消息以防验证失败,因此添加 ErrorMessage="* Alphabets Only" 以便如果有人输入数字,它将显示此消息

 <asp:TextBox runat="server" ID="txtSurname"></asp:TextBox>
        <asp:RegularExpressionValidator runat="server" ID="txtSurnameValidation" 
     ControlToValidate="txtSurname" ValidationExpression="[a-zA-Z ]*$" ErrorMessage="* Alphabets Only" Display="Dynamic">
</asp:RegularExpressionValidator>

【讨论】:

    【解决方案2】:

    可能在这里回答:Prevent numbers from being pasted in textbox in .net windows forms

    基本上,您可以点击 TextChanged 事件以不允许输入或粘贴数字。您也可以处理 KeyDown 和 KeyUp 事件,但它们不会防止您粘贴数字。因此 TextChanged 是首选和推荐。

    string _latestValidText = string.Empty;
    private void TextBox_TextChanged(object sender, EventArgs e)
    {
        TextBox target = sender as TextBox;
        if (ContainsNumber(target.Text))
        {
            // display alert and reset text
            MessageBox.Show("The text may not contain any numbers.");
            target.Text = _latestValidText;
        }
        else
        {
            _latestValidText = target.Text;
        }
    }
    private static bool ContainsNumber(string input)
    {
        return Regex.IsMatch(input, @"\d+");
    }
    

    【讨论】:

    • 问题被标记为asp.net - 你不想在每次按键时都往返于服务器,MessageBox.Show 也没有用 - 即使它确实有效,它也会显示消息在服务器上,而不是在运行浏览器的机器上。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-12
    • 1970-01-01
    • 2011-11-09
    • 1970-01-01
    • 2010-12-16
    • 1970-01-01
    相关资源
    最近更新 更多