Files
mtusi2026lab3/app/internal/common/validation.go
T

100 lines
1.9 KiB
Go

package common
import (
"regexp"
"strings"
"unicode/utf8"
"github.com/google/uuid"
)
var usernameRegex = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
func blank(s string) bool {
return strings.TrimSpace(s) == ""
}
func strLenBetween(s string, min, max int) bool {
n := utf8.RuneCountInString(s)
return n >= min && n <= max
}
func ValidateCreateUser(username, displayName string) string {
if !usernameRegex.MatchString(username) {
return "username must match ^[a-z0-9_]{3,32}$"
}
if blank(displayName) {
return "display_name must not be empty or only whitespace"
}
if !strLenBetween(displayName, 1, 100) {
return "display_name must be between 1 and 100 Unicode code points"
}
return ""
}
func ValidatePassword(password string) string {
if blank(password) {
return "password must not be empty or only whitespace"
}
if !strLenBetween(password, 12, 128) {
return "password must be between 12 and 128 Unicode code points"
}
return ""
}
func ValidateChatTitle(title string) string {
if blank(title) {
return "title must not be empty or only whitespace"
}
if !strLenBetween(title, 1, 100) {
return "title must be between 1 and 100 Unicode code points"
}
return ""
}
func ValidateMessageText(text string) string {
if blank(text) {
return "text must not be empty or only whitespace"
}
if !strLenBetween(text, 1, 4000) {
return "text must be between 1 and 4000 Unicode code points"
}
return ""
}
func ValidateMemberIDs(ids []uuid.UUID, callerID uuid.UUID) string {
if len(ids) < 1 || len(ids) > 100 {
return "member_ids must contain between 1 and 100 members"
}
seen := make(map[uuid.UUID]bool, len(ids))
callerFound := false
for _, id := range ids {
if seen[id] {
return "member_ids must not contain duplicates"
}
seen[id] = true
if id == callerID {
callerFound = true
}
}
if !callerFound {
return "caller must be included in member_ids"
}
return ""
}