How to restrict user from typing certain numbers in input field
Hey. I'm creating some sort of a numeration system and I don't want the user to type certain numbers, say for example I don't want the user to type the number 8 inside the input field, how do I do this through code or inside the editor?
Answer by lvskiprof · Oct 05, 2020 at 11:01 PM
In your script you can only process the valid digits, based on what is valid at the time. Throw invalid ones away.
Sorry for the slow replay back. In my case I am using the Input.inputString() method, so the user has to enter the response and use the Enter key. I then check the list of valid responses for my current state and act on it if it is valid and show the list of valid response if it is not and wait for a now response.
If you are using Input.GetKeyDown() I am not sure how you could consume an invalid key, but probably doing a KeyKeyDown() for all the possible invalid keys would do that. So handle all digits, but have some way to flag which are the valid keys. That will likely consume the invalid keys as well as the valid keys and you don't process the invalid ones or issue a beep for them to let the user know they are invalid.
Answer by drewjosh · Oct 06, 2020 at 07:16 AM
Either you handle the not allowed digits inside a separate if-statement and you show an error message in the UI or you only handle only the once that are allowed. For better user experience I recommend to do the first. How to retrieve the pressed key on the keyboard you find in the docs: https://docs.unity3d.com/ScriptReference/Input.GetKeyDown.html
Answer by janmolbech · Oct 06, 2020 at 09:04 PM
You should look into using regular expressions https://www.c-sharpcorner.com/article/c-sharp-regex-examples/ It is much easier to control if the number of chars you want to disallow increases
Your answer
Follow this Question
Related Questions
How do I let users change the background color of a selected word in an input field? 0 Answers
Using PlayerPrefs to store string but it won't update on my UI 1 Answer
Convert Message to Text Field Input 0 Answers
InputField not able to hold long text 2 Answers
UI Text created from C# Script 0 Answers