Validating user input

Hello! I couldn’t find any threads about this on the forums.

What is the best way to validate user input in “real time”?

I do not want the user to be able to type in the TextField if the button he presses is not a number.

Would it be to check the current key which is being pressed, or maybe make a regex?

Either that or constantly watch the text field’s display string removing any non-numeric characters (again, using regular expressions being the path of choice).

Allright, thanks :slight_smile:

Ended up doing this:

using UnityEngine;
using System.Text.RegularExpressions;

public class ValidateInputTest: MonoBehaviour 
{
 Regex numberRegex = new Regex("[0-9]");
 Rect numberPosition = new Rect(10, 10, 20, 20);
 string numberText = "";

void OnGUI()
{
 if (numberRegex.IsMatch(Input.inputString))
  numberText = GUI.TextField(numberPosition, numberText, 2);
 else
  GUI.TextField(numberPosition, numberText, 2);
}
}

How would you go about doing this in Javascript? I tried using:

using UnityEngine; 
using System.Text.RegularExpressions;

And it throws an error on the first line, so im assuming this is MonoScript? Is there a Javascript equivalent?

It’s C#. In Javascript, use “import” instead of “using”. Also you don’t need to import UnityEngine (that’s automatic).

–Eric