- Home /
Allow only numbers in an input field
I want to know how to restrict the input field numbers and just ignore the letters, I found it but the method of "int" does not exist, or rather "int" does not exist. I Program in C #
GUI.Label(new Rect(positionX, positionY, _W, _H), "Epaisseur (mm):");
stringToEditH = GUI.TextField (new Rect (positionX, positionY+_H, _W/3f, 20f), num.ToString(), 3);
int temp = 0;
if (int.TryParse(stringToEditH, temp))
{
num = Mathf.Clamp(0, temp);
}
else if (text == "") num = 0;
I would also like to know if it is possible to edit the value of the textfield at click on an object, put the value of the field.
Assets/Standard Assets/Scripts/Utility Scripts/$$anonymous$$ain.cs(271,37): error CS1502: The best overloaded method match for `int.TryParse(string, out int)' has some invalid arguments
//(my "stringToEditH" is declared as a string)
this is the last error i get. Time to sleep :) thx
You will get that error if you try to call int.TryParse on a string that doesn't represent a valid integer.
Answer by jahroy · Dec 08, 2011 at 12:20 AM
It's very easy if you want to use a regex:
I don't usually use C#, but a quick look at the documentation makes me think it would look like this:
/* define a pattern: everything but 0-9 */
Regex rgx = new Regex("[^0-9]");
/ replace all non-numeric characters with an empty string /
stringToEditH = rgx.Replace(stringToEditH, "");
You might have to fiddle with it, but that's the idea....
------------
If you don't want to use a regex, you could do it yourself like this:
function stripNonNumerics ( inputString : String ) : String { var theResult : String = "";
for ( var i = 0; i < inputString.length; i ++ ) {
var theString : String = inputString.Substring(i, 1);
var tempInt : int;
if ( int.TryParse(theString, tempInt) ) {
theResult += theString;
}
}
return theResult;
}
There are probably a few better ways to do it, but that seems to work for me.
That's in UnityScript... it will probably be easier in C# where you can use chars!!
You have to add the Regex library if you want to use its functions.
I believe you need to add the following to the top of your script:
using System.Text.RegularExpressions;
... or something like that.
That's why I said if you want to use a regex.
If you don't want to include that library (but get the same result) you can use the second example I gave.