48 lines
899 B
Go
48 lines
899 B
Go
package validator
|
|
|
|
import (
|
|
"slices"
|
|
"strings"
|
|
"unicode/utf8"
|
|
)
|
|
|
|
type Validator struct {
|
|
FieldErrors map[string]string
|
|
}
|
|
|
|
// Valid() ...
|
|
func (v *Validator) Valid() bool {
|
|
return len(v.FieldErrors) == 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
|
|
}
|
|
}
|
|
|
|
// 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
|
|
}
|
|
|
|
// PermittedValue[T comparable] ...
|
|
func PermittedValue[T comparable](value T, permittedValues ...T) bool {
|
|
return slices.Contains(permittedValues, value)
|
|
}
|