survey
survey copied to clipboard
Support for decimals and integers
Hi, there is a "default" way to deal with numeric input? Didn't find anything on the way to prevent letters/non-numeric input, or to force the user to set a valid number.
Using the survey.Input
with a int/float the user can type letters, and it fails with a "Atoi error".
What is the proper way to deal with getting a valid integer or float value.
👋 This is what validator functions are for: https://github.com/AlecAivazis/survey#validation
However, if the destination var/field for a survey input is an int or float, maybe it would be better to initialize such prompts with an implicit validator for those types of numbers so that the user never gets the conversion error. Would that make sense? Was that what you were suggesting?
yes i think it would be better if a validator were assigned to the input if the answer var was a int/float.
if possible prevent typing non-numeric characters to show in the input, or allow a formatting function to apply a mask to the input, maybe allowing a custom OnRune function to clean-up/mask the input on the go. https://github.com/AlecAivazis/survey/blob/13bc976fcb6cbda74df02d33044677ea9d6ab86b/terminal/runereader.go#L34
It is possible to declare an int
or float
value receiver and have Survey automatically convert the string response into the desired type:
var age int
err := survey.AskOne(&survey.Input{Message: "What is your age?"}, &age)
If the user has typed invalid characters that trip up ParseInt/ParseFloat functions, Survey will error out. To instead ensure that the user will be prompted again until they use valid inputs, validator functions can be used (per my previous comment).