Restrict characters in GUI.TextField

Hi. How could I ban some letters from being typed into a TextField? For example, for a UserName field, the player can't write charaters like "[]{}!@#$%&*()", etc. How could I prevent the player to type those characters into the TextField?

Thanks in advance.

There are lots of ways to do this, but the best way is to use RegEx.

You'd want to use something like this:

using System.Text.RegularExpressions; // needed for Regex

public class TextBox : MonoBehaviour
     string text;

     void OnGUI()
          text = GUI.TextField(..., text);
          text = Regex.Replace(text, @"[^a-zA-Z0-9 ]", "");

That code will only allow characters a-z, A-Z, 0-9, and a space (" "). If you want to include other characters, you can add them inside the brackets, like this:

`[^a-zA-Z0-9 #!@]`

But be sure to leave the ^ at the start of the brackets.

MSDN Reference for Regex:

The problem with System.Text.RegularExpressions is that it adds about 900K to web player sizes, because of having to add .dlls that aren't normally included. Also doing regex string replacements every frame in OnGUI may not be ideal for performance. If you're not using a web player then you probably wouldn't care, but if you are, you would likely be better off preventing the unwanted characters from entering the string in the first place and not using regex:

void OnGUI () {
    char chr = Event.current.character;
    if ( (chr < 'a' || chr > 'z') && (chr < 'A' || chr > 'Z') && (chr < '0' || chr > '9') ) {
        Event.current.character = '\0';
    text = GUILayout.TextField(text, GUILayout.Width(500));

That replaces any input character not in the a-z, A-Z, and 0-9 range with a null character.

There may be a more efficient way, but an easy way is:

private string enteredString = "";
private char[] badChars = { '[', ']', '{', '}', '!', '@', '#', '$', '%', '', '&', '*', '(', ')', '', '', '', '', '', '', '' };

void OnGUI()
  string newString = GUILayout.TextField( enteredString );
  if( newString.IndexOfAny( badChars ) < 0 )
    enteredString = newString;

Hi @Bruno,

You can use ContentType property on input field. Say, you want only alphabets to be typed in your input field as name for that you can use Name variable. You can put the following line of code in Start function for that:

InputFieldref.contentType = InputField.ContentType.Name;

Using above line enforces capitalisation and the InputField is used for typing in a name.