10

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

Federal09
  • 639
  • 4
  • 9
  • 25
  • 2
    What kind of text box? WinForms? WPF? ASP.NET? Windows 8 Store? – Jon Skeet Oct 22 '13 at 17:06
  • Please add some code to your question of what you have tried. – Black Frog Oct 22 '13 at 17:12
  • string one = radTextBoxControl1.Text.Replace("/", ""); string two = one.Replace("%", ""); //more string radTextBoxControl1.Text = two; – Federal09 Oct 22 '13 at 17:17
  • radTextBoxControl indicates that you're using the Telerik control. Why not just use the masked edit control instead. As an aside I would much rather fail a validation that have random keys not do anything. Also why can't you allow those values? – Conrad Frix Oct 22 '13 at 18:43

7 Answers7

19

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;
    }
}
Hossain Muctadir
  • 3,546
  • 1
  • 19
  • 33
  • 6
    If you use a whitelist for the set of allowed characters you will need to include control characters as well. Otherwise shortcuts like `Ctrl+C` won't work anymore. `Char.IsControl(e.KeyChar)` should help with this. – Chaquotay May 13 '14 at 16:42
  • 3
    If you use the regex in the solution the backspace key will not work, should you need to make use of the backspace then the regex should be var regex = new Regex(@"[^a-zA-Z0-9\s[\b]]"); – Geovani Martinez Oct 21 '15 at 16:54
  • Will the keypress be useful if the input has been copied and pasted? – Bharath theorare Jun 19 '16 at 08:19
  • Perhaps the TextChanged event may be more appropiate. – B.Hawkins Jul 24 '18 at 09:25
6

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

6

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
KidBilly
  • 3,408
  • 1
  • 26
  • 40
  • 1
    To extend this solution to check for any other specifically required characters, in addition to those already checked for, you could just add the Linq contains statement. E.g. To also allow an underscore, dash and hash: `&& !"-_#".Contains(e.KeyChar)` – StuKay Jan 21 '22 at 12:27
0

You could use the 'Text Changed' event (I BELIEVE (but am not sure) that this gets fired on a copy/paste).

When the event is triggered call a method, let's say, PurgeTextOfEvilCharacters().

In this method have an array of the characters you want to "block". Go through each character of the .Text of the TextBox control and if the character is found in your array then you don't want it. Rebuild the string with the "okay" characters and you're good to go.

I'm betting there's a better way, but this seems okay to me!

Andrew Mack
  • 302
  • 3
  • 13
0

the best for me:

void textBoxSample_KeyPress(object sender, KeyPressEventArgs e)
    {
        e.Handled = Char.IsPunctuation(e.KeyChar) ||  
                      Char.IsSeparator(e.KeyChar) || 
                      Char.IsSymbol(e.KeyChar);
    }

it will be more usefull to enable delete and backsapce Keys ...etc

Hisham
  • 1,279
  • 1
  • 17
  • 23
0

we can validate it using regular expression validator

ValidationExpression="^[\sa-zA-Z0-9]*$"

<asp:TextBox runat="server" ID="txtname" />
        <asp:RegularExpressionValidator runat="server" ControlToValidate="txtname"
            ForeColor="Red" SetFocusOnError="true" Display="Dynamic"
            ErrorMessage=" Restrict for special characters" ID="rfvname"
            ValidationExpression="^[\sa-zA-Z0-9]*$">

        </asp:RegularExpressionValidator>

you can see also demo here https://www.neerajcodesolutions.com/2018/05/how-to-restrict-special-characters-in.html

Pooja
  • 1
  • It would be good if you also described briefly in your answer what a regular expression is, or link to an explanation. In case OP doesn't know it. – Doh09 Jun 12 '18 at 20:15
0

Another way to exclude a varied selection of characters such as %,&,',A,b,2 would be to use the following in the TextBox KeyPress event handler:

e.Handled = "%&'Ab2".Contains(e.KeyChar.ToString());

To include a double quote to the exclusion list use:

e.Handled = ("%&'Ab2"+'"').Contains(e.KeyChar.ToString());

Note: This is case sensitive.

StuKay
  • 307
  • 1
  • 7