0

I have an input field and I want it to only accept English letters, numbers, and symbols. How can I do that?

Hamid Yusifli
  • 8,125
  • 2
  • 20
  • 45
Itai Elidan
  • 223
  • 8
  • 21
  • Does this answer your question? [form validation allow only english alphabet characters](https://stackoverflow.com/questions/15304790/form-validation-allow-only-english-alphabet-characters) – Hamid Yusifli Nov 23 '20 at 20:58
  • Not really, I can't use regex because I don't want non english letters to be inputed from the first place. I want only english letters real time. Could you show me a solution that involves the other one for a real time update? – Itai Elidan Nov 23 '20 at 21:03
  • Afaik you can in the Inspector or by code simply set its [`contentType`](https://docs.unity3d.com/2018.2/Documentation/ScriptReference/UI.InputField-contentType.html) to [`ContentType.Custom`](https://docs.unity3d.com/2018.2/Documentation/ScriptReference/UI.InputField.ContentType.Custom.html) and then define an alphabet that is allowed as input – derHugo Nov 24 '20 at 00:21

1 Answers1

2

Add a listener that changes the input field's value when it detects a change in value. And in that listener, set the value to be the same as the input but any non-compliant characters removed:

[SerializeField] InputField inputField;

void OnEnable()
{
    //Register InputField Event
    inputField.onValueChanged.AddListener(inputValueChanged});
}


static string CleanInput(string strIn)
{
    // Replace invalid characters with empty strings.
    return Regex.Replace(strIn,
          @"[^a-zA-Z0-9`!@#$%^&*()_+|\-=\\{}\[\]:"";'<>?,./]", ""); 
}

//Called when Input changes
void inputValueChanged(string attemptedVal)
{
    inputField.text = CleanInput(attemptedVal);
}

void OnDisable()
{
    //Un-Register InputField Events
    inputField.onValueChanged.RemoveAllListeners();
}

Sources:

Ruzihm
  • 19,133
  • 4
  • 34
  • 44