more username validation

trunk
vilmibm 2023-02-28 23:44:34 +00:00
parent 8716140b40
commit 9442ecb55e
1 changed files with 19 additions and 1 deletions

View File

@ -4,6 +4,7 @@ import (
"errors"
"fmt"
"os"
"regexp"
"strings"
"git.tilde.town/tildetown/town/invites"
@ -43,17 +44,34 @@ func promptCode() (code string, err error) {
}
func promptUsername(townData stats.TildeData) (un string, err error) {
usernameRE := regexp.MustCompile(`^[a-z][-a-z0-9_]*$`)
unPrompt := &survey.Input{
Message: "desired username?",
}
err = survey.AskOne(unPrompt, &un,
survey.WithValidator(survey.Required),
survey.WithIcons(surveyIconSet),
survey.WithValidator(func(val interface{}) error {
un := val.(string)
if len(un) > 32 {
return fmt.Errorf("username '%s' is too long", un)
}
return nil
}),
survey.WithValidator(func(val interface{}) error {
un := val.(string)
if !usernameRE.MatchString(un) {
return errors.New("usernames must start with a letter and only contain letters, nubers, - or _")
}
return nil
}),
survey.WithValidator(func(val interface{}) error {
un := val.(string)
for _, v := range townData.Users {
if v.Username == un {
return errors.New("that username is already in use, sorry")
return fmt.Errorf("username '%s' is already in use", un)
}
}
return nil