Reputation:
How can I limit my textbox to only accept numbers and letters? It should not even allow spaces or anything like "!", "?", "/" and so on. Only a-z, A-Z, 0-9
Tried this and it did not work at all
if (System.Text.RegularExpressions.Regex.IsMatch(@"^[a-zA-Z0-9\_]+", txtTag.Text))
{
txtTag.Text.Remove(txtTag.Text.Length - 1);
}
Not even sure if that txtTag.Text.Remove(txtTag.Text.Length - 1);
should be there because it makes the application crash.
Upvotes: 2
Views: 29641
Reputation: 13
try this code for the letter and numbers:
Void textbox1_KeyPress(object sender,KeyPressEventArgs e) {
// allows only letters or numbers
if (!Char.IsLetterOrDigit(e.KeyChar))
{
e.Handled = true;
}
}
Upvotes: 0
Reputation: 63
try this
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = !char.IsLetter(e.KeyChar) && !char.IsControl(e.KeyChar)
&& !char.IsSeparator(e.KeyChar) && !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar);
}
Upvotes: 2
Reputation: 406
My thought is you could alter the KeyPressed or TextChanged events for that control to check if the characters entered are numbers or letters. For example, to check the characters as they are added in the textbox you could do something like the following :
myTextbox.KeyPress += new KeyPressEventHandler(myTextbox_KeyPress);
void myTextbox_KeyPress(object sender, KeyPressEventArgs e)
{
if(e.KeyChar >= Keys.A && e.KeyChar <= Keys.Z)
// you can then modify the text box text here
Upvotes: 1
Reputation: 4010
First of all, check out this article for some information.
I think what you should do on the client side is to add the pattern
attribute in the corresponding HTML.
<input type="text" name="foo" pattern="[a-zA-Z0-9_]" title="Please input only letters and numbers">
Upvotes: -2
Reputation: 9201
You don't need a regex for that:
textBox1.Text = string.Concat(textBox1.Text.Where(char.IsLetterOrDigit));
This will remove everything that is not a letter or digit, and can be placed in the TextChanged event. Basically, it gets the text, splits it into characters and only pick what is a letter or digit. After that, we can concatenate it back to a string.
Also, if you'd like to place the caret at the end of the textbox (because changing the text will reset its position to 0), you may also add textBox1.SelectionStart = textBox1.Text.Length + 1;
Upvotes: 11