gouick/helpers/input/string.go
Matthieu 'JP' DERASSE dccbb30a85
All checks were successful
continuous-integration/drone/push Build is passing
feat(input): Full refacto of the user input system
2022-09-16 20:22:19 +00:00

67 lines
1.8 KiB
Go

package input
import (
"fmt"
"net/mail"
"regexp"
)
var (
// RegexAlphanumerical is a basic alphanumerical regex to be use in RegexInput function.
RegexAlphanumerical = regexp.MustCompile(`^[a-zA-Z0-9\-\_]*$`)
// RegexAlphanumericalAndSpace is a basic alphanumerical regex with space as an additionnal valid character to be use in RegexInput function.
RegexAlphanumericalAndSpace = regexp.MustCompile(`^[a-zA-Z0-9\-\_\s]*$`)
)
// Regex permit to ask user for an input and check that it match the given regex rule.
// if not user will see the errMsg and be asked for another input.
func Regex(mandatory bool, regex *regexp.Regexp, errMsg string) string {
value := Ask(mandatory, func(in string) (string, error) {
if !regex.MatchString(in) {
return "", fmt.Errorf("%s", errMsg)
}
return in, nil
})
return value
}
// Alphanumerical will ask user for an input respecting the RegexAlphanumerical.
func Alphanumerical(mandatory bool) string {
return Regex(mandatory, RegexAlphanumerical, "Please use a-z, A-Z, 0-9, - and _ characters only.")
}
// AlphanumericalAndSpace will ask user for an input respecting the RegexAlphanumericalAndSpace.
func AlphanumericalAndSpace(mandatory bool) string {
return Regex(mandatory, RegexAlphanumericalAndSpace, "Please use a-z, A-Z, 0-9, -, _ and space characters only.")
}
// String permit to ask user for any kind of string.
func String(mandatory bool) string {
value := Ask(mandatory, func(in string) (string, error) {
return in, nil
})
return value
}
// Mail permit to ask user for an email address.
func Mail(mandatory bool) string {
value := Ask(mandatory, func(in string) (string, error) {
_, err := mail.ParseAddress(in)
if err != nil {
return "", fmt.Errorf("expecting a valid mail address, please try again")
}
return in, nil
})
return value
}