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?

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.