charles david
charles david

Reputation: 51

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>

Upvotes: 3

Views: 688

Answers (2)

Usman
Usman

Reputation: 4703

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>

Upvotes: 3

Akshay Mahajan
Akshay Mahajan

Reputation: 190

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

Upvotes: 0

Related Questions