- Home /
How do I use custom input validation on an InputField?
I see options for Standard, Alphanumeric, Password, PIN, etc. At the bottom is one called Custom, which I assumed would allow me to input RegEx or a function or something I could use to prevent certain characters from being entered. However, the documentation doesn't say anything about this.
I would like to only allow alphanumeric plus spaces and underscores; how can I do this?
Answer by cief · Apr 28, 2020 at 01:40 PM
I was looking for an answer to this earlier today. It can be done in a C# script by setting a function to the InputField's onValidateInput property. The function is then called when a character is typed into the inputfield.
The function's parameters are: string text, int charIndex, char addedChar
. addedChar is the character that was just typed and needs to be validated. The function has to return a char to be added to the InputField text; it can return addedChar if it's acceptable, or can return '\0' to reject it.
In my function I reject chars that meet this check (not a letter, not a number, not in allowed list):
if (!char.IsLetter(addedChar) && !char.IsNumber(addedChar) && !allowedPunctuation.Contains(addedChar))
where allowedPunctuation is a List<char>
containing the punctuation characters that I want to allow, such as empty space, hyphen, and apostrophe.
Your answer
Follow this Question
Related Questions
How do I get the Text Mesh Pro UGUI working in a prefab? 1 Answer
UI text visual glitching 1 Answer
comparing a number input to a letter input 3 Answers
GUI using custom graphics - GUI approuches 1 Answer
UI Text Small on screen device. 1 Answer