简体   繁体   中英

How to not allow user to input numbers in textbox

I am trying to make a textbox that doesn't allow to input numbers

I have tried some codes but doesn't work

Here is what I have tried:

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

its working but its not showing any message because you did not set any message in case validation fails so add ErrorMessage="* Alphabets Only" so that if someone enters numbers it will show this message

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

Probably answered here: Prevent numbers from being pasted in textbox in .net windows forms

Basically, you can tap in TextChanged event to not allow numbers to be typed in or pasted. You can also work off of KeyDown and KeyUp events but they won't guard you against pasting numbers. Hence TextChanged is preferred and recommended.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM