Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a TextBox accept only alphabetic characters?

How can I make a TextBox only accept alphabetic characters with spaces?

like image 971
Lijina Avatar asked Nov 30 '11 06:11

Lijina


2 Answers

You can try by handling the KeyPress event for the textbox

void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back);
}

Additionally say allow backspace in case you want to remove some text, this should work perfectly fine for you

EDIT

The above code won't work for paste in the field for which i believe you will have to use TextChanged event but then it would be a bit more complicated with you having to remove the incorrect char or highlight it and place the cursor for the user to make the correction Or maybe you could validate once the user has entered the complete text and tabs off the control.

like image 86
V4Vendetta Avatar answered Oct 19 '22 03:10

V4Vendetta


You could use the following snippet:

private void textBox1_TextChanged(object sender, EventArgs e)
{
    if (!System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, "^[a-zA-Z ]"))
    {
        MessageBox.Show("This textbox accepts only alphabetical characters");
        textBox1.Text.Remove(textBox1.Text.Length - 1);
    }
}
like image 29
favoretti Avatar answered Oct 19 '22 03:10

favoretti