survey icon indicating copy to clipboard operation
survey copied to clipboard

Support for decimals and integers

Open lucassabreu opened this issue 3 years ago • 3 comments

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.

lucassabreu avatar Nov 01 '21 20:11 lucassabreu

👋 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?

mislav avatar Nov 01 '21 20:11 mislav

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

lucassabreu avatar Nov 01 '21 20:11 lucassabreu

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).

mislav avatar Oct 17 '22 12:10 mislav