s1llyw0rdz/web/handler/form/register.go

51 lines
1.1 KiB
Go
Raw Normal View History

2021-11-22 09:06:23 +00:00
package form
import (
"errors"
"net/http"
"regexp"
)
2021-11-22 13:00:19 +00:00
type RegisterForm struct {
2021-12-10 17:48:24 +00:00
Username string
Password string
Email string
ShowEmail bool
Answer string
Confirm string
Key string
Error string
2021-11-22 09:06:23 +00:00
}
2021-11-22 13:00:19 +00:00
func (f *RegisterForm) Validate() error {
2021-11-22 09:06:23 +00:00
if f.Password != f.Confirm {
return errors.New("password doesn't match confirmation")
}
if len(f.Username) < 3 {
return errors.New("username needs to be at least 3 characters")
}
2021-12-22 09:21:14 +00:00
if len(f.Username) > 20 {
return errors.New("username should be 20 characters or less")
}
2021-11-22 09:06:23 +00:00
match, _ := regexp.MatchString("^[a-z0-9-_]+$", f.Username)
if !match {
return errors.New("only lowercase letters and digits are accepted for username")
}
if len(f.Password) < 6 {
return errors.New("password needs to be at least 6 characters")
}
return nil
}
2021-11-22 13:00:19 +00:00
func NewRegisterForm(r *http.Request) *RegisterForm {
return &RegisterForm{
2021-12-10 17:48:24 +00:00
Username: r.FormValue("name"),
Password: r.FormValue("password"),
Confirm: r.FormValue("password-confirm"),
Email: r.FormValue("email"),
ShowEmail: r.FormValue("show-email") == "1",
Answer: r.FormValue("answer"),
Key: r.FormValue("key"),
2021-11-22 09:06:23 +00:00
}
}