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?
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.
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:
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: