Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to block or restrict special characters from textbox

Tags:

c#

winforms

I need exclude special characters (%,&,/,",' etc ) from textbox

Is it possible? Should I use key_press event?

string one = radTextBoxControl1.Text.Replace("/", "");
                string two = one.Replace("%", "");
                //more string
                radTextBoxControl1.Text = two;

in this mode is very very long =(

like image 719
Federal09 Avatar asked Oct 22 '13 17:10

Federal09


People also ask

How do I not allow special characters in HTML?

click(function(){ var fn = $("#folderName"). val(); var regex = /^[0-9a-zA-Z\_]+$/ alert(regex. test(fn)); }); }); This return false for special chars and spaces and return true for underscore, digits and alphabets.


3 Answers

you can use this:

private void textBoxSample_KeyPress(object sender, KeyPressEventArgs e)
    {
        e.Handled = !char.IsLetter(e.KeyChar) && !char.IsDigit(e.KeyChar);
    }

it blocks special characters and only accept int/numbers and characters

like image 100
Francis Acosta Avatar answered Oct 22 '22 15:10

Francis Acosta


I am assuming you are trying to keep only alpha-numeric and space characters. Add a keypress event like this

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    var regex = new Regex(@"[^a-zA-Z0-9\s]");
    if (regex.IsMatch(e.KeyChar.ToString()))
    {
        e.Handled = true;
    }
}
like image 30
Hossain Muctadir Avatar answered Oct 22 '22 14:10

Hossain Muctadir


The code below allows only numbers, letters, backspace and space.

I included VB.net because there was a tricky conversion I had to deal with.

C#

private void textBoxSample_KeyPress(object sender, KeyPressEventArgs e)
{
    e.Handled = e.KeyChar != (char)Keys.Back && !char.IsSeparator(e.KeyChar) && !char.IsLetter(e.KeyChar) && !char.IsDigit(e.KeyChar);
}

VB.net

Private Sub textBoxSample_KeyPress(sender As Object, e As KeyPressEventArgs) Handles textBoxSample.KeyPress
    e.Handled = e.KeyChar <> ChrW(Keys.Back) And Not Char.IsSeparator(e.KeyChar) And Not Char.IsLetter(e.KeyChar) And Not Char.IsDigit(e.KeyChar) 
End Sub
like image 21
KidBilly Avatar answered Oct 22 '22 14:10

KidBilly