- Home /
Stopping Copy/paste into Textfield.
Does anyone know of a way to stop a user from pasting text into a text field? We have a situation where we want users to type into a text field, but not paste into a text field.
The only way I could think of was to look at the text in a text field and if it changed by more than one character set it back to its prior text (but I don't know if it's possible to type fast enough that a user could theoretically have more than one character entered by the next time I draw the TextField and examine its contents. I'm hoping for something that would let me do this in a better way.
Thanks.
Answer by ben · Mar 09, 2011 at 09:54 AM
It will Work
using UnityEngine; using System.Collections; using System.Text.RegularExpressions;
public class RestrictCharsInTextField : MonoBehaviour {
public string text;
void OnGUI() { text = GUI.TextField(new Rect(100,100,100,50), text, 10); text = Regex.Replace(text, @"[^a-zA-Z0-9.@ ]", "");
if(Event.current.command || Event.current.control){ // cmd - for Mac control - for windows
text = "";
}
}
}
This won't stop using Shift-Insert key combination on Windows.
We use the Event.current.command check but also cache the string and revert it if its length has increased by more than 1, to catch the Shift-Insert case.
In our case, the call's being made frequently enough for this to still allow fast typing, including repeated chars by holding a key down, as queried in the OP. But I guess that could vary, you'd have to try it.
Answer by Statement · Mar 07, 2011 at 11:49 PM
Well, a brittle idea is to cause some sort of invalidation upon CTRL down (for CTRL + V shortcut). I don't know if it is feasible, but you could perhaps disable the text field for a second or so if that button is pressed, and clean out any value entered.
Or if it is possible, just set the text to string.Empty
when Event.current.control == true
. I haven't tried this myself, you'll have to check if it works or not.
Answer by yoyo · Mar 08, 2011 at 05:24 AM
This almost works (C#) ...
string noPaste = "";
void OnGUI()
{
string temp = GUILayout.TextField(noPaste);
if (!Event.current.control)
noPaste = temp;
}
It prevents pasting, but the text cursor still moves when the paste is performed. Not sure how to fix that part.
Your answer
Follow this Question
Related Questions
Cannot copy, select or paste in TextField on Android 0 Answers
Copy text in TextField to windows clipboard 2 Answers
How do I keep a texture different on copied objects? 1 Answer
Why cant I copy anything I have in my Project Tab to the Hierarchy Tab or Scene? 1 Answer
login window with user name 1 Answer