2024-10-23 05:25:30 +00:00
|
|
|
package validator
|
|
|
|
|
|
|
|
import (
|
2024-11-11 19:55:01 +00:00
|
|
|
"regexp"
|
2024-10-23 05:25:30 +00:00
|
|
|
"slices"
|
|
|
|
"strings"
|
|
|
|
"unicode/utf8"
|
|
|
|
)
|
|
|
|
|
2024-11-11 19:55:01 +00:00
|
|
|
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])?)*$")
|
|
|
|
|
2024-10-23 05:25:30 +00:00
|
|
|
type Validator struct {
|
2024-11-11 19:55:01 +00:00
|
|
|
NonFieldErrors []string
|
2024-10-23 05:25:30 +00:00
|
|
|
FieldErrors map[string]string
|
|
|
|
}
|
|
|
|
|
|
|
|
func (v *Validator) Valid() bool {
|
2024-11-11 19:55:01 +00:00
|
|
|
return len(v.FieldErrors) == 0 && len(v.NonFieldErrors) == 0
|
2024-10-23 05:25:30 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
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
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-11-11 19:55:01 +00:00
|
|
|
func (v *Validator) AddNonFieldError(message string) {
|
|
|
|
v.NonFieldErrors = append(v.NonFieldErrors, message)
|
|
|
|
}
|
|
|
|
|
2024-10-23 05:25:30 +00:00
|
|
|
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 PermittedValue[T comparable](value T, permittedValues ...T) bool {
|
|
|
|
return slices.Contains(permittedValues, value)
|
|
|
|
}
|
2024-11-11 19:55:01 +00:00
|
|
|
|
|
|
|
func MinChars(value string, n int) bool {
|
|
|
|
return utf8.RuneCountInString(value) >= n
|
|
|
|
}
|
|
|
|
|
|
|
|
func Matches(value string, rx *regexp.Regexp) bool {
|
|
|
|
return rx.MatchString(value)
|
|
|
|
}
|