forked from mtusi2026/mtusi2026lab6
81 lines
1.4 KiB
Go
81 lines
1.4 KiB
Go
package validate
|
|
|
|
import (
|
|
"fmt"
|
|
"regexp"
|
|
"strings"
|
|
"unicode/utf8"
|
|
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
const (
|
|
UsernameMinLen = 3
|
|
UsernameMaxLen = 32
|
|
|
|
DisplayNameMinLen = 1
|
|
DisplayNameMaxLen = 100
|
|
|
|
PasswordMinLen = 12
|
|
PasswordMaxLen = 128
|
|
|
|
ChatTitleMinLen = 1
|
|
ChatTitleMaxLen = 100
|
|
|
|
MessageTextMaxLen = 4000
|
|
|
|
MemberIDsMin = 1
|
|
MemberIDsMax = 100
|
|
|
|
LimitMin = 1
|
|
LimitMax = 100
|
|
LimitDefault = 50
|
|
)
|
|
|
|
var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
|
|
|
func CanonicalUUID(field, s string) (string, error) {
|
|
if len(s) != 36 {
|
|
return "", newError(field, "must be a valid UUID")
|
|
}
|
|
u, err := uuid.Parse(s)
|
|
if err != nil {
|
|
return "", newError(field, "must be a valid UUID")
|
|
}
|
|
return u.String(), nil
|
|
}
|
|
|
|
func Limit(n int) error {
|
|
if n < LimitMin || n > LimitMax {
|
|
return newError("limit", fmt.Sprintf("must be in [%d, %d]", LimitMin, LimitMax))
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func codePointsBetween(s string, min, max int) bool {
|
|
n := utf8.RuneCountInString(s)
|
|
return n >= min && n <= max
|
|
}
|
|
|
|
func notOnlyWhitespace(s string) bool {
|
|
return strings.TrimSpace(s) != ""
|
|
}
|
|
|
|
type Error struct {
|
|
Field string
|
|
Reason string
|
|
}
|
|
|
|
func (e *Error) Error() string {
|
|
return e.Field + ": " + e.Reason
|
|
}
|
|
|
|
func (e *Error) Is(target error) bool {
|
|
_, ok := target.(*Error)
|
|
return ok
|
|
}
|
|
|
|
func newError(field, reason string) *Error {
|
|
return &Error{Field: field, Reason: reason}
|
|
}
|