AlecAivazis / survey

A golang library for building interactive and accessible prompts with full support for windows and posix terminals.
MIT License
4.07k stars 351 forks source link

Support for decimals and integers #388

Open lucassabreu opened 2 years ago

lucassabreu commented 2 years ago

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.

mislav commented 2 years ago

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

lucassabreu commented 2 years ago

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

mislav commented 1 year ago

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