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.

3 Answers

3

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.

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.

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 = "";
        }
 }

}

always welcome!

Question: could someone still macro around this?

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.