learn-go/snippetbox/internal/validator/validator.go
2024-02-07 16:27:03 -08:00

65 lines
1.4 KiB
Go

package validator
import (
"regexp"
"slices"
"strings"
"unicode/utf8"
)
var EmailRX = regexp.MustCompile("^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$")
type Validator struct {
NonFieldErrors []string
FieldErrors map[string]string
}
// Valid() ...
func (v *Validator) Valid() bool {
return len(v.FieldErrors) == 0 && len(v.NonFieldErrors) == 0
}
// AddFieldError ...
func (v *Validator) AddFieldError(key, message string) {
if v.FieldErrors == nil {
v.FieldErrors = make(map[string]string)
}
if _, exists := v.FieldErrors[key]; !exists {
v.FieldErrors[key] = message
}
}
func (v *Validator) AddNonFieldError(message string) {
v.NonFieldErrors = append(v.NonFieldErrors, message)
}
// CheckField ...
func (v *Validator) CheckField(ok bool, key, message string) {
if !ok {
v.AddFieldError(key, message)
}
}
func NotBlank(value string) bool {
return strings.TrimSpace(value) != ""
}
func MaxChars(value string, n int) bool {
return utf8.RuneCountInString(value) <= n
}
func MinChars(value string, n int) bool {
return n <= utf8.RuneCountInString(value)
}
// Matches ...
func Matches(value string, rx *regexp.Regexp) bool {
return rx.MatchString(value)
}
// PermittedValue[T comparable] ...
func PermittedValue[T comparable](value T, permittedValues ...T) bool {
return slices.Contains(permittedValues, value)
}