Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Validating user input

Discussion in 'Immediate Mode GUI (IMGUI)' started by Sbd, Jul 31, 2008.

  1. Sbd

    Sbd

    Joined:
    Jun 16, 2008
    Posts:
    36
    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?
     
  2. HiggyB

    HiggyB

    Unity Product Evangelist

    Joined:
    Dec 8, 2006
    Posts:
    6,183
    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).
     
  3. Sbd

    Sbd

    Joined:
    Jun 16, 2008
    Posts:
    36
    Allright, thanks :)

    Ended up doing this:

    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Text.RegularExpressions;
    4.  
    5. public class ValidateInputTest: MonoBehaviour
    6. {
    7.  Regex numberRegex = new Regex("[0-9]");
    8.  Rect numberPosition = new Rect(10, 10, 20, 20);
    9.  string numberText = "";
    10.  
    11. void OnGUI()
    12. {
    13.  if (numberRegex.IsMatch(Input.inputString))
    14.   numberText = GUI.TextField(numberPosition, numberText, 2);
    15.  else
    16.   GUI.TextField(numberPosition, numberText, 2);
    17. }
    18. }
    19.  
    20.  
     
  4. Fishypants

    Fishypants

    Joined:
    Jan 25, 2009
    Posts:
    444
    How would you go about doing this in Javascript? I tried using:

    Code (csharp):
    1. using UnityEngine;
    2. using System.Text.RegularExpressions;
    And it throws an error on the first line, so im assuming this is MonoScript? Is there a Javascript equivalent?
     
  5. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,369
    It's C#. In Javascript, use "import" instead of "using". Also you don't need to import UnityEngine (that's automatic).

    --Eric