- Home /
[New UI 4.6] InputField - validate input to only permit positive integers.
I am using an InputField component, and I wish to restrict the input to be only positive integers.
I can use inputField.validation = InputField.Validation.Integer; to restrict input to integers, but how can I extend this to allow only positive integers?
Thanks in advance...
Answer by Landern · Oct 26, 2014 at 05:30 PM
Use onValidateInput and ensure the input is not a string and only positive numbers:
Thanks for the quick reply, Landern, but there's no actual documentation there except the function name. How does one go about using it? I see in my code that the function defintion is:
public delegate char OnValidateInput(string text, int charIndex, char addedChar);
what is expected in the input params? I'm not sure how to use this...
I believe you would handle this by simply declaring a function that matches the signature. Same as OnCollisionEnter or Update.
I could be wrong.
thanks, I understand what you mean about matching the signature, I was able to use
void Start()
{
InputField inputField = gameObject.GetComponent<InputField>();
inputField.validation = InputField.Validation.Integer;
inputField.onValidateInput += ValidateInput;
}
public char ValidateInput(string text, int charIndex, char addedChar)
{
char temp = 'c';
return temp;
}
I still don't understand what the char return value signifies though...
In any case, my inputFields are not even accepting any input since I just updated to the 21 beta, so I need to figure out what's going wrong there before I can continue with validation. $$anonymous$$any thanks for your help.
Answer by fingerbib · Oct 29, 2014 at 09:42 PM
Here is my own solution, it's a bit clunky, but using the OnValidation delegate seems to override any inbuilt validation (i.e. InputField.validation no longer screens for non ints)
void Start() { inputField = gameObject.GetComponent(); inputField.validation = InputField.Validation.Integer;
inputField.onValidateInput += ValidateInput;
}
public char ValidateInput(string text, int charIndex, char addedChar) { char output = addedChar;
if (addedChar != '1'
&& addedChar != '2'
&& addedChar != '3'
&& addedChar != '4'
&& addedChar != '5'
&& addedChar != '6'
&& addedChar != '7'
&& addedChar != '8'
&& addedChar != '9'
&& addedChar != '0')
{
//return a null character
output = '\0';
}
return output;
}
There's a shorter way ;):
output = Regex.Replace(addedChar+"",@"[0-9]","\0"); //"output" is a String
return output.ToCharArray()[0];
This doesn't let you type 0 to 9. If you only want to allow 0-9 but nothing else, you can use:
"[^0-9]"
Don't forget to add:
using System.Text.RegularExpressions;
Your answer

Follow this Question
Related Questions
[4.6 UI] Image fading - How to? 2 Answers
How do I add a mesh to a button object in 4.6b? 0 Answers
[4.6 - UI] Accessing Text in Image inside Canvas via C# Script 3 Answers
[4.6 - UI] Keep aspect ratio 2 Answers
4.6 play animation on game over 0 Answers