more username validation

pull/1/head
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" "errors"
"fmt" "fmt"
"os" "os"
"regexp"
"strings" "strings"
"git.tilde.town/tildetown/town/invites" "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) { func promptUsername(townData stats.TildeData) (un string, err error) {
usernameRE := regexp.MustCompile(`^[a-z][-a-z0-9_]*$`)
unPrompt := &survey.Input{ unPrompt := &survey.Input{
Message: "desired username?", Message: "desired username?",
} }
err = survey.AskOne(unPrompt, &un, err = survey.AskOne(unPrompt, &un,
survey.WithValidator(survey.Required), survey.WithValidator(survey.Required),
survey.WithIcons(surveyIconSet), 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 { survey.WithValidator(func(val interface{}) error {
un := val.(string) un := val.(string)
for _, v := range townData.Users { for _, v := range townData.Users {
if v.Username == un { 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 return nil