package helper
import (
"encoding"
"encoding/json/v2"
"fmt"
"reflect"
"strconv"
"time"
)
var textUnmarshalerType = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem()
func AnyToFloat(v any) (float64, error) {
switch v := v.(type) {
case nil:
// A null value has no length, so it counts as 0
return 0, nil
case string:
return float64(len(v)), nil
case time.Time:
return float64(v.Unix()), nil
case int:
return float64(v), nil
case int8:
return float64(v), nil
case int16:
return float64(v), nil
case int32:
return float64(v), nil
case int64:
return float64(v), nil
case uint:
return float64(v), nil
case uint8:
return float64(v), nil
case uint16:
return float64(v), nil
case uint32:
return float64(v), nil
case uint64:
return float64(v), nil
case float32:
return float64(v), nil
case float64:
return v, nil
default:
rv := reflect.ValueOf(v)
switch rv.Type().Kind() {
case reflect.Array, reflect.Slice, reflect.Map:
return float64(rv.Len()), nil
default:
return 0, fmt.Errorf("unsupported type for value: %T", v)
}
}
}
func AnyToString(v any) (string, error) {
switch v := v.(type) {
case string:
return v, nil
case bool:
return fmt.Sprintf("%t", v), nil
case time.Time:
return fmt.Sprintf("%d", v.Unix()), nil
case int, int8, int16, int32, int64,
uint, uint8, uint16, uint32, uint64:
return fmt.Sprintf("%d", v), nil
case float32, float64:
return fmt.Sprintf("%v", v), nil
case encoding.TextMarshaler:
// A nil pointer still implements the interface, but calling it would panic.
if rv := reflect.ValueOf(v); rv.Kind() == reflect.Ptr && rv.IsNil() {
return "", fmt.Errorf("unsupported nil value: %T", v)
}
text, err := v.MarshalText()
if err != nil {
return "", fmt.Errorf("error marshaling value to text: %v", err)
}
return string(text), nil
default:
return "", fmt.Errorf("unsupported type for value: %T", v)
}
}
func AnyToArrayOfString(v any) ([]string, error) {
if v, ok := v.([]string); ok {
return v, nil
}
rv := reflect.ValueOf(v)
switch rv.Type().Kind() {
case reflect.Array, reflect.Slice:
values := []string{}
rv := reflect.ValueOf(v)
for i := 0; i < rv.Len(); i++ {
avs, err := AnyToString(rv.Index(i).Interface())
if err != nil {
return nil, fmt.Errorf("error converting array value to string: %T", v)
}
values = append(values, avs)
}
return values, nil
case reflect.Map:
keys := []string{}
for _, mk := range reflect.ValueOf(v).MapKeys() {
mks, err := AnyToString(mk.Interface())
if err != nil {
return nil, fmt.Errorf("error converting map key to string: %T", v)
}
keys = append(keys, mks)
}
return keys, nil
default:
return nil, fmt.Errorf("unsupported type for value: %T", v)
}
}
func AnyToType(in any, expected reflect.Type) (out any, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("error converting interface to type %v: %v", expected, r)
}
}()
// Nil input
if in == nil {
// For maps and slices, return empty collections instead of nil to prevent panics
if expected.Kind() == reflect.Map {
return reflect.MakeMap(expected).Interface(), nil
}
if expected.Kind() == reflect.Slice {
return reflect.MakeSlice(expected, 0, 0).Interface(), nil
}
return reflect.Zero(expected).Interface(), nil
}
// Direct type match or assignable
inType := reflect.TypeOf(in)
if inType == expected {
return in, nil
}
if inType.AssignableTo(expected) {
return in, nil
}
// Handle pointer types by recursively converting to the element type,
// then returning a pointer to the result
if expected.Kind() == reflect.Ptr {
if s, ok := in.(string); ok && s == "" {
return reflect.Zero(expected).Interface(), nil
}
elemType := expected.Elem()
elemValue, err := AnyToType(in, elemType)
if err != nil {
return nil, err
}
// Create a pointer to the converted value
ptrValue := reflect.New(elemType)
ptrValue.Elem().Set(reflect.ValueOf(elemValue))
return ptrValue.Interface(), nil
}
switch expKind := expected.Kind(); expKind {
case reflect.String:
if v, ok := in.(string); ok {
// Check if we need to convert to a custom string type
if reflect.TypeOf(in).ConvertibleTo(expected) {
return reflect.ValueOf(in).Convert(expected).Interface(), nil
}
return v, nil
}
// If it's another basic value, we can safely convert to string
strVal, err := AnyToString(in)
if err == nil {
if reflect.TypeOf(strVal).ConvertibleTo(expected) {
return reflect.ValueOf(strVal).Convert(expected).Interface(), nil
}
return strVal, nil
}
case reflect.Bool:
if v, ok := in.(bool); ok {
// Check if we need to convert to a custom bool type
if reflect.TypeOf(in).ConvertibleTo(expected) {
return reflect.ValueOf(in).Convert(expected).Interface(), nil
}
return v, nil
} else if v, ok := in.(string); ok {
switch v {
// Case on and off are for form values.
case "on":
return any(true), nil
case "off":
return any(false), nil
default:
b, err := strconv.ParseBool(v)
if err != nil {
return nil, fmt.Errorf("error parsing string to bool: %v", err)
}
return any(b), nil
}
}
case reflect.Int:
if v, ok := in.(int); ok {
return v, nil
} else if v, ok := in.(float64); ok {
return any(int(v)), nil
} else if v, ok := in.(string); ok {
if v == "" {
return any(int(0)), nil
}
i, err := strconv.ParseInt(v, 10, 64)
if err != nil {
return nil, fmt.Errorf("error parsing string to int64: %v", err)
}
return any(int(i)), nil
} else if reflect.TypeOf(in).ConvertibleTo(expected) {
return reflect.ValueOf(in).Convert(expected).Interface(), nil
}
case reflect.Int8:
if v, ok := in.(int8); ok {
return v, nil
} else if v, ok := in.(float64); ok {
return any(int8(v)), nil
} else if v, ok := in.(string); ok {
if v == "" {
return any(int8(0)), nil
}
i, err := strconv.ParseInt(v, 10, 8)
if err != nil {
return nil, fmt.Errorf("error parsing string to int8: %v", err)
}
return any(int8(i)), nil
} else if reflect.TypeOf(in).ConvertibleTo(expected) {
return reflect.ValueOf(in).Convert(expected).Interface(), nil
}
case reflect.Int16:
if v, ok := in.(int16); ok {
return v, nil
} else if v, ok := in.(float64); ok {
return any(int16(v)), nil
} else if v, ok := in.(string); ok {
if v == "" {
return any(int16(0)), nil
}
i, err := strconv.ParseInt(v, 10, 16)
if err != nil {
return nil, fmt.Errorf("error parsing string to int16: %v", err)
}
return any(int16(i)), nil
} else if reflect.TypeOf(in).ConvertibleTo(expected) {
return reflect.ValueOf(in).Convert(expected).Interface(), nil
}
case reflect.Int32:
if v, ok := in.(int32); ok {
return v, nil
} else if v, ok := in.(float64); ok {
return any(int32(v)), nil
} else if v, ok := in.(string); ok {
if v == "" {
return any(int32(0)), nil
}
i, err := strconv.ParseInt(v, 10, 32)
if err != nil {
return nil, fmt.Errorf("error parsing string to int32: %v", err)
}
return any(int32(i)), nil
} else if reflect.TypeOf(in).ConvertibleTo(expected) {
return reflect.ValueOf(in).Convert(expected).Interface(), nil
}
case reflect.Int64:
if v, ok := in.(int64); ok {
return v, nil
} else if v, ok := in.(float64); ok {
return any(int64(v)), nil
} else if v, ok := in.(string); ok {
if v == "" {
return any(int64(0)), nil
}
i, err := strconv.ParseInt(v, 10, 64)
if err != nil {
return nil, fmt.Errorf("error parsing string to int64: %v", err)
}
return any(int64(i)), nil
} else if reflect.TypeOf(in).ConvertibleTo(expected) {
return reflect.ValueOf(in).Convert(expected).Interface(), nil
}
case reflect.Uint:
if v, ok := in.(uint); ok {
return v, nil
} else if v, ok := in.(float64); ok {
return any(uint(v)), nil
} else if v, ok := in.(string); ok {
if v == "" {
return any(uint(0)), nil
}
u, err := strconv.ParseUint(v, 10, 64)
if err != nil {
return nil, fmt.Errorf("error parsing string to uint64: %v", err)
}
return any(uint(u)), nil
} else if reflect.TypeOf(in).ConvertibleTo(expected) {
return reflect.ValueOf(in).Convert(expected).Interface(), nil
}
case reflect.Uint8:
if v, ok := in.(uint8); ok {
return v, nil
} else if v, ok := in.(float64); ok {
return any(uint8(v)), nil
} else if v, ok := in.(string); ok {
if v == "" {
return any(uint8(0)), nil
}
u, err := strconv.ParseUint(v, 10, 8)
if err != nil {
return nil, fmt.Errorf("error parsing string to uint8: %v", err)
}
return any(uint8(u)), nil
} else if reflect.TypeOf(in).ConvertibleTo(expected) {
return reflect.ValueOf(in).Convert(expected).Interface(), nil
}
case reflect.Uint16:
if v, ok := in.(uint16); ok {
return v, nil
} else if v, ok := in.(float64); ok {
return any(uint16(v)), nil
} else if v, ok := in.(string); ok {
if v == "" {
return any(uint16(0)), nil
}
u, err := strconv.ParseUint(v, 10, 16)
if err != nil {
return nil, fmt.Errorf("error parsing string to uint16: %v", err)
}
return any(uint16(u)), nil
} else if reflect.TypeOf(in).ConvertibleTo(expected) {
return reflect.ValueOf(in).Convert(expected).Interface(), nil
}
case reflect.Uint32:
if v, ok := in.(uint32); ok {
return v, nil
} else if v, ok := in.(float64); ok {
return any(uint32(v)), nil
} else if v, ok := in.(string); ok {
if v == "" {
return any(uint32(0)), nil
}
u, err := strconv.ParseUint(v, 10, 32)
if err != nil {
return nil, fmt.Errorf("error parsing string to uint32: %v", err)
}
return any(uint32(u)), nil
} else if reflect.TypeOf(in).ConvertibleTo(expected) {
return reflect.ValueOf(in).Convert(expected).Interface(), nil
}
case reflect.Uint64:
if v, ok := in.(uint64); ok {
return v, nil
} else if v, ok := in.(float64); ok {
return any(uint64(v)), nil
} else if v, ok := in.(string); ok {
if v == "" {
return any(uint64(0)), nil
}
u, err := strconv.ParseUint(v, 10, 64)
if err != nil {
return nil, fmt.Errorf("error parsing string to uint64: %v", err)
}
return u, nil
} else if reflect.TypeOf(in).ConvertibleTo(expected) {
return reflect.ValueOf(in).Convert(expected).Interface(), nil
}
case reflect.Float32:
if v, ok := in.(float32); ok {
return v, nil
} else if v, ok := in.(float64); ok {
return any(float32(v)), nil
} else if v, ok := in.(string); ok {
if v == "" {
return any(float32(0)), nil
}
f, err := strconv.ParseFloat(v, 32)
if err != nil {
return nil, fmt.Errorf("error parsing string to float32: %v", err)
}
return any(float32(f)), nil
} else if reflect.TypeOf(in).ConvertibleTo(expected) {
return reflect.ValueOf(in).Convert(expected).Interface(), nil
}
case reflect.Float64:
if v, ok := in.(float64); ok {
return v, nil
} else if v, ok := in.(string); ok {
if v == "" {
return any(float64(0)), nil
}
f, err := strconv.ParseFloat(v, 64)
if err != nil {
return nil, fmt.Errorf("error parsing string to float64: %v", err)
}
return any(float64(f)), nil
} else if reflect.TypeOf(in).ConvertibleTo(expected) {
return reflect.ValueOf(in).Convert(expected).Interface(), nil
}
case reflect.Struct:
if v, ok := in.(time.Time); ok {
return v, nil
} else if v, ok := in.(float64); ok {
date, err := UnixStringToTime(strconv.Itoa(int(v)))
if err != nil {
return nil, fmt.Errorf("error parsing float to time.Time: %v", err)
}
return date, nil
} else if v, ok := in.(string); ok {
structTempt := reflect.New(expected).Interface()
if err := json.Unmarshal([]byte(v), structTempt); err != nil {
date, err := UnixStringToTime(v)
if err != nil {
date, err = ISO8601StringToTime(v)
if err != nil {
return nil, fmt.Errorf("error parsing string to struct: %v", err)
}
}
return date, nil
}
return reflect.ValueOf(structTempt).Elem().Interface(), nil
} else if jsonValueMap, ok := in.(map[string]any); ok {
structTemp := reflect.New(expected).Interface()
err = MapJsonMapToStruct(jsonValueMap, structTemp)
if err != nil {
return nil, fmt.Errorf("error parsing map to struct: %v", err)
}
return reflect.ValueOf(structTemp).Elem().Interface(), nil
} else if reflect.TypeOf(in).ConvertibleTo(expected) {
return reflect.ValueOf(in).Convert(expected).Interface(), nil
}
case reflect.Map:
if v, ok := in.(map[string]any); ok {
mapValue, err := JsonMapToMapKV(v, expected.Key(), expected.Elem())
if err != nil {
return nil, err
}
return mapValue.Interface(), nil
} else if reflect.TypeOf(in).ConvertibleTo(expected) {
return reflect.ValueOf(in).Convert(expected).Interface(), nil
}
case reflect.Array, reflect.Slice:
if inArray, ok := in.([]any); ok {
return anyArrayToType(inArray, expected)
} else if strValue, ok := in.(string); ok {
// Types like uuid.UUID or net.IP know how to parse themselves from text
if reflect.PointerTo(expected).Implements(textUnmarshalerType) {
target := reflect.New(expected)
err := target.Interface().(encoding.TextUnmarshaler).UnmarshalText([]byte(strValue))
if err == nil {
return target.Elem().Interface(), nil
}
// Raw bytes of matching length are still accepted for byte arrays (e.g. 16 bytes for uuid.UUID)
if expected.Kind() != reflect.Array || expected.Elem().Kind() != reflect.Uint8 || len(strValue) != expected.Len() {
return nil, fmt.Errorf("error parsing string to %v: %v", expected, err)
}
}
// Special case: if expected is []byte or [N]byte, convert string to byte array/slice
if expected.Elem().Kind() == reflect.Uint8 {
if expected.Kind() == reflect.Slice {
return []byte(strValue), nil
} else if expected.Kind() == reflect.Array {
byteSlice := []byte(strValue)
arrayValue := reflect.New(expected).Elem()
for i := 0; i < expected.Len() && i < len(byteSlice); i++ {
arrayValue.Index(i).SetUint(uint64(byteSlice[i]))
}
return arrayValue.Interface(), nil
}
}
}
// Handle array/slice of other types
if inType.ConvertibleTo(expected) && !(expected.Kind() == reflect.Array && inType.Kind() == reflect.Slice) {
return reflect.ValueOf(in).Convert(expected).Interface(), nil
}
// Typed array/slice (e.g. []string into []int): convert element by element.
if inKind := inType.Kind(); inKind == reflect.Array || inKind == reflect.Slice {
inArray, err := ArrayToArrayOfAny(in)
if err != nil {
return nil, err
}
return anyArrayToType(inArray, expected)
}
// A lone value (e.g. a single form value) is treated as a one-element list,
// so the struct field type decides whether it becomes a slice.
return anyArrayToType([]any{in}, expected)
case reflect.Interface:
return in, nil
default:
return nil, fmt.Errorf("unsupported type %T", expected)
}
return nil, fmt.Errorf("unsupported type %T", expected)
}
// anyArrayToType converts each element of in to the element type of expected
// and returns a value of type expected (slice or fixed-size array).
func anyArrayToType(in []any, expected reflect.Type) (any, error) {
if expected.Kind() == reflect.Array && len(in) > expected.Len() {
return nil, fmt.Errorf("too many elements for %v: got %d, max %d", expected, len(in), expected.Len())
}
typedArray, err := ArrayToArrayOfType(in, expected.Elem())
if err != nil {
return nil, err
}
if expected.Kind() == reflect.Array {
arrayValue := reflect.New(expected).Elem()
reflect.Copy(arrayValue, typedArray)
return arrayValue.Interface(), nil
}
if typedArray.Type() != expected {
// Named slice types like `type Kinds []Kind`
return typedArray.Convert(expected).Interface(), nil
}
return typedArray.Interface(), nil
}
package helper
import (
"fmt"
"reflect"
)
func ArrayToArrayOfAny(v any) ([]any, error) {
aany := []any{}
rv := reflect.ValueOf(v)
if !rv.IsValid() {
return nil, fmt.Errorf("invalid nil value, has to be array or slice")
}
if rv.Type().Kind() != reflect.Array && rv.Type().Kind() != reflect.Slice {
return nil, fmt.Errorf("invalid type %v, has to be array or slice", rv.Type().Kind())
}
for i := 0; i < rv.Len(); i++ {
aany = append(aany, rv.Index(i).Interface())
}
return aany, nil
}
func ArrayToArrayOfType(a []any, expectedValue reflect.Type) (reflect.Value, error) {
targetArray := reflect.MakeSlice(reflect.SliceOf(expectedValue), len(a), len(a))
for i, item := range a {
itemConverted, err := AnyToType(item, expectedValue)
if err != nil {
return reflect.Value{}, fmt.Errorf("error converting item at index %d: %v", i, err)
}
targetArray.Index(i).Set(reflect.ValueOf(itemConverted))
}
return targetArray, nil
}
package helper
import (
"fmt"
"reflect"
)
// Checks if the given value is a string.
func IsString(in any) bool {
return in != nil && reflect.TypeOf(in).Kind() == reflect.String
}
// Checks if the given value is a struct.
func IsStruct(in any) bool {
return in != nil && reflect.TypeOf(in).Kind() == reflect.Struct
}
// Checks if the given value is an array or slice.
func IsArray(in any) bool {
return in != nil && (reflect.TypeOf(in).Kind() == reflect.Array || reflect.TypeOf(in).Kind() == reflect.Slice)
}
// Checks if the given value is an array or slice of structs.
func IsArrayOfStruct(in any) bool {
return IsArray(in) && reflect.TypeOf(in).Elem().Kind() == reflect.Struct
}
// Checks if the given value is an array of maps.
func IsArrayOfMap(in any) bool {
return IsArray(in) && reflect.TypeOf(in).Elem().Kind() == reflect.Map
}
// Checks if the given value is a pointer to a struct.
func CheckValidPointerToStruct(in any) error {
value := reflect.ValueOf(in)
if value.Kind() != reflect.Ptr {
return fmt.Errorf("value has to be of kind pointer, was %T", value)
}
if value.Elem().Kind() != reflect.Struct {
return fmt.Errorf("value has to be of kind struct, was %T", value)
}
return nil
}
package helper
import (
"fmt"
"reflect"
"strings"
)
func ConditionValueToT[T comparable](v T, condition string) (T, error) {
rt := reflect.TypeOf(v)
out, err := AnyToType(condition, rt)
if err != nil {
return v, fmt.Errorf("error converting condition value: %v", err)
}
return out.(T), nil
}
func ConditionValueToArrayOfAny(condition string, expected reflect.Type) ([]any, error) {
conditionList := strings.Split(condition, ",")
if len(conditionList) == 0 || (len(conditionList) == 1 && len(strings.TrimSpace(conditionList[0])) == 0) {
return []any{}, fmt.Errorf("empty condition list %s value", condition)
}
values := []any{}
for _, c := range conditionList {
ct, err := AnyToType(any(c), expected)
if err != nil {
return nil, fmt.Errorf("error converting map key to string: %v", err)
}
values = append(values, any(ct))
}
return values, nil
}
package helper
import (
"reflect"
"strings"
)
// FieldKey resolves the map key and tag options of a struct field.
// The key is taken from the json tag, falls back to the yaml tag and then to the field name.
// A tag name of "-" or "" keeps the field name as key, StructModelOf leaves out fields tagged with `json:"-"`.
// The options omitempty and inline are read from the same tag the key is resolved from.
// `embed` (the name of the option in encoding/json/v2) is the same as `inline`.
func FieldKey(fieldType reflect.StructField) (key string, omitEmpty bool, inline bool) {
key = fieldType.Name
tag := fieldType.Tag.Get("json")
if len(tag) == 0 {
tag = fieldType.Tag.Get("yaml")
}
if len(tag) == 0 {
return key, false, false
}
// strings.Cut instead of strings.Split, because this runs for every field on every
// Validate call and Split allocates a slice for every tag.
name, options, _ := strings.Cut(tag, ",")
if name != "-" && name != "" {
key = name
}
for options != "" {
var option string
option, options, _ = strings.Cut(options, ",")
switch option {
case "omitempty":
omitEmpty = true
case "inline", "embed":
inline = true
}
}
return key, omitEmpty, inline
}
package helper
import (
"encoding"
"encoding/json/v2"
"fmt"
"reflect"
)
func GetValidMap(in any) (map[string]any, error) {
v, ok := in.(map[string]any)
if ok {
return v, nil
}
return nil, fmt.Errorf("error getting valid map from json")
}
// UnmapStructToJsonMap writes the fields of the given struct pointer into the JsonMap.
// The keys are taken from the StructModel of the struct, so embedded and inline structs are flattened.
// Nested structs (also behind pointers) and slices/arrays of structs are converted recursively
// to JsonMaps (and []any of JsonMaps), so their inner validations can be run like for json input.
// Fields promoted from a nil embedded pointer are not written, they are missing like in json.
// Structs implementing encoding.TextMarshaler (eg. time.Time) are kept as they are.
func UnmapStructToJsonMap(structInput any, jsonMapToUpdate *map[string]any) error {
err := CheckValidPointerToStruct(structInput)
if err != nil {
return err
}
unmapStructValue(reflect.ValueOf(structInput).Elem(), *jsonMapToUpdate)
return nil
}
var textMarshalerType = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem()
// unmapStructValue writes the fields of the struct value into the JsonMap.
func unmapStructValue(structValue reflect.Value, jsonMap map[string]any) {
for _, field := range StructModelOf(structValue.Type()).Fields {
value, ok := fieldForRead(structValue, field.Index)
if ok {
jsonMap[field.Key] = unmapValue(value)
}
}
}
// unmapValue converts a struct (or pointer to struct) to a JsonMap
// and a slice/array of structs to a []any of JsonMaps. All other values are returned as they are.
func unmapValue(value reflect.Value) any {
switch value.Kind() {
case reflect.Ptr:
if value.Type().Elem().Kind() == reflect.Struct && !isTextMarshalerStruct(value.Type().Elem()) {
if value.IsNil() {
return nil
}
return unmapValue(value.Elem())
}
case reflect.Struct:
if !isTextMarshalerStruct(value.Type()) {
jsonMap := map[string]any{}
unmapStructValue(value, jsonMap)
return jsonMap
}
case reflect.Slice, reflect.Array:
if value.Type().Elem().Kind() == reflect.Struct && !isTextMarshalerStruct(value.Type().Elem()) {
if value.Kind() == reflect.Slice && value.IsNil() {
return nil
}
array := make([]any, value.Len())
for i := 0; i < value.Len(); i++ {
array[i] = unmapValue(value.Index(i))
}
return array
}
}
return value.Interface()
}
// isTextMarshalerStruct reports if the struct type (or its pointer) implements encoding.TextMarshaler.
func isTextMarshalerStruct(structType reflect.Type) bool {
return structType.Implements(textMarshalerType) || reflect.PointerTo(structType).Implements(textMarshalerType)
}
func JsonMapToMapKV(m map[string]any, expectedKey reflect.Type, expectedValue reflect.Type) (reflect.Value, error) {
targetMapValue := reflect.MakeMap(reflect.MapOf(expectedKey, expectedValue))
for key, value := range m {
valueConverted, err := AnyToType(value, expectedValue)
if err != nil {
return reflect.Value{}, fmt.Errorf("error converting value for key %s: %v", key, err)
}
keyConverted, err := AnyToType(key, expectedKey)
if err != nil {
return reflect.Value{}, fmt.Errorf("error converting key %s: %v", key, err)
}
targetMapValue.SetMapIndex(reflect.ValueOf(keyConverted), reflect.ValueOf(valueConverted))
}
return targetMapValue, nil
}
// MapJsonMapToStruct writes the values of the JsonMap into the given struct pointer.
// The keys are taken from the StructModel of the struct, so embedded and inline structs are flattened
// and nil embedded pointers are set if one of their fields is written. Only keys in the JsonMap are written,
// nested JsonMaps are written into the existing nested struct. Nil maps and slices of missing keys are set to empty ones.
//
// Values are converted with AnyToType. Fields with an own UnmarshalJSON or the json options `string` or `format:`
// are written with encoding/json instead (see StructModelOf).
func MapJsonMapToStruct(jsonMapInput map[string]any, structToUpdate any) error {
err := CheckValidPointerToStruct(structToUpdate)
if err != nil {
return err
}
return mapJsonMapToStructValue(jsonMapInput, reflect.ValueOf(structToUpdate).Elem())
}
func mapJsonMapToStructValue(jsonMapInput map[string]any, structValue reflect.Value) error {
for _, field := range StructModelOf(structValue.Type()).Fields {
jsonValue, ok := jsonMapInput[field.Key]
if !ok {
initEmpty(structValue, field)
continue
}
target := fieldForWrite(structValue, field.Index)
var err error
if field.decodeType != nil {
err = decodeJSON(target, field.decodeType, jsonValue)
} else if jsonValueMap, isMap := jsonValue.(map[string]any); isMap && isStructOrPointer(target.Type()) {
if target.Kind() == reflect.Ptr {
if target.IsNil() {
target.Set(reflect.New(target.Type().Elem()))
}
target = target.Elem()
}
err = mapJsonMapToStructValue(jsonValueMap, target)
if err != nil {
return fmt.Errorf("error mapping nested struct %v: %v", field.Field.Name, err)
}
continue
} else if jsonArray, isArray := jsonValue.([]any); isArray && isSliceOfMaps(jsonArray, target.Type()) {
err = mapJsonArrayToSlice(jsonArray, target)
} else {
err = SetStructValueByJson(target, jsonValue)
}
if err != nil {
return fmt.Errorf("could not set field %v (json key: %v) of %v: %v", field.Field.Name, field.Key, structValue.Type(), err)
}
}
return nil
}
// initEmpty sets a nil map or slice field to an empty one to prevent panics.
// Fields behind a nil embedded pointer are not set, so the pointer stays nil.
func initEmpty(structValue reflect.Value, field StructField) {
kind := field.Field.Type.Kind()
if kind != reflect.Map && kind != reflect.Slice {
return
}
value, ok := fieldForRead(structValue, field.Index)
if !ok || !value.CanSet() || !value.IsNil() {
return
}
if kind == reflect.Map {
value.Set(reflect.MakeMap(value.Type()))
} else {
value.Set(reflect.MakeSlice(value.Type(), 0, 0))
}
}
// isSliceOfMaps reports if all items of the array are JsonMaps and the target is a slice of structs.
func isSliceOfMaps(jsonArray []any, target reflect.Type) bool {
if target.Kind() != reflect.Slice || target.Elem().Kind() != reflect.Struct {
return false
}
for _, item := range jsonArray {
if _, ok := item.(map[string]any); !ok {
return false
}
}
return true
}
// mapJsonArrayToSlice writes the JsonMaps of the array into a new slice of structs, like AnyToType does,
// but without converting every item on its own.
func mapJsonArrayToSlice(jsonArray []any, target reflect.Value) error {
slice := reflect.MakeSlice(target.Type(), len(jsonArray), len(jsonArray))
for i, item := range jsonArray {
err := mapJsonMapToStructValue(item.(map[string]any), slice.Index(i))
if err != nil {
return fmt.Errorf("error converting item at index %d: %v", i, err)
}
}
target.Set(slice)
return nil
}
func isStructOrPointer(t reflect.Type) bool {
return t.Kind() == reflect.Struct || (t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Struct)
}
// decodeJSON writes the value into the field with encoding/json, by decoding it into a struct
// of the given decodeType that has the field (with its json options) as only field.
// The field keeps its current value as base, like encoding/json does for existing structs and maps.
func decodeJSON(target reflect.Value, decodeType reflect.Type, jsonValue any) error {
encoded, err := json.Marshal(map[string]any{"V": jsonValue})
if err != nil {
return fmt.Errorf("error marshaling value: %v", err)
}
wrapper := reflect.New(decodeType)
wrapper.Elem().Field(0).Set(target)
err = json.Unmarshal(encoded, wrapper.Interface())
if err != nil {
return err
}
target.Set(wrapper.Elem().Field(0))
return nil
}
func SetStructValueByJson(fv reflect.Value, jsonValue any) (err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("error setting struct value: %v", r)
}
}()
if fv.IsValid() && fv.CanSet() {
converted, err := AnyToType(jsonValue, fv.Type())
if err != nil {
return err
}
fv.Set(reflect.ValueOf(converted))
}
return nil
}
package helper
import (
"fmt"
"reflect"
)
func MapKeysToArrayOfAny(v any) ([]any, error) {
aany := []any{}
rv := reflect.ValueOf(v)
if !rv.IsValid() {
return nil, fmt.Errorf("invalid nil value, has to be map")
}
if rv.Type().Kind() != reflect.Map {
return nil, fmt.Errorf("invalid type %v, has to be map", rv.Type().Kind())
}
for _, mk := range rv.MapKeys() {
aany = append(aany, mk.Interface())
}
return aany, nil
}
// MapValue returns the value of the given key in a map with string keys (eg. a JsonMap or map[string]string).
// ok is false if the key does not exist or v is not a map with string keys.
func MapValue(v any, key string) (any, bool) {
if m, ok := v.(map[string]any); ok {
value, ok := m[key]
return value, ok
}
rv := reflect.ValueOf(v)
if rv.Kind() != reflect.Map || rv.Type().Key().Kind() != reflect.String {
return nil, false
}
value := rv.MapIndex(reflect.ValueOf(key).Convert(rv.Type().Key()))
if !value.IsValid() {
return nil, false
}
return value.Interface(), true
}
package helper
import (
"encoding/json/v2"
"reflect"
"sort"
"strings"
"sync"
"time"
)
// StructModel describes how a struct type looks as a JsonMap.
// It is the single source for the keys of a struct, used for reading (UnmapStructToJsonMap),
// writing (MapJsonMapToStruct) and the extraction of validations, so all of them behave the same.
type StructModel struct {
Type reflect.Type
Fields []StructField
}
// StructField is a field of a StructModel.
type StructField struct {
// Key is the key of the field in the JsonMap (see FieldKey).
Key string
// Index is the index path of the field (see reflect.Value.FieldByIndex),
// it has more than one element for fields promoted from embedded or inline structs.
Index []int
OmitEmpty bool
// Field is the struct field itself.
Field reflect.StructField
// decodeType is set for fields that are written by encoding/json (see needsJSONDecode).
// It is a struct with the field as only field `V`, so the json options of the field are kept.
decodeType reflect.Type
}
var structModelCache sync.Map
// StructModelOf returns the cached StructModel of the given struct type.
//
// The fields follow the rules of encoding/json:
// - Unexported fields and fields tagged with `json:"-"` (or `yaml:"-"` without json tag) are left out.
// - Embedded structs (also behind pointers) without a name in the tag and fields tagged with `inline` or `embed`
// are flattened into the parent. Exported fields of unexported embedded structs are promoted too.
// - If several fields have the same key, the shallowest one wins. At the same depth the field with a name
// in the tag wins, otherwise all of them are left out.
//
// Recursive types are fine, a struct is only flattened once.
func StructModelOf(structType reflect.Type) *StructModel {
if cached, ok := structModelCache.Load(structType); ok {
return cached.(*StructModel)
}
structModel := &StructModel{Type: structType, Fields: structFields(structType)}
cached, _ := structModelCache.LoadOrStore(structType, structModel)
return cached.(*StructModel)
}
type structLevel struct {
structType reflect.Type
index []int
}
type fieldCandidate struct {
field StructField
named bool
}
// structFields collects the fields of the struct type level by level (breadth first) like encoding/json,
// so the depth of a field is known for resolving conflicting keys.
func structFields(structType reflect.Type) []StructField {
candidates := []fieldCandidate{}
visited := map[reflect.Type]bool{}
next := []structLevel{{structType: structType}}
for len(next) > 0 {
current := next
next = nil
for _, level := range current {
if visited[level.structType] {
continue
}
visited[level.structType] = true
for i := 0; i < level.structType.NumField(); i++ {
field := level.structType.Field(i)
if !isModelField(field) {
continue
}
index := make([]int, len(level.index)+1)
copy(index, level.index)
index[len(level.index)] = i
key, omitEmpty, inline := FieldKey(field)
named := hasTagName(field)
fieldType := field.Type
if fieldType.Kind() == reflect.Ptr {
fieldType = fieldType.Elem()
}
if fieldType.Kind() == reflect.Struct && (inline || (field.Anonymous && !named)) {
next = append(next, structLevel{structType: fieldType, index: index})
continue
}
candidates = append(candidates, fieldCandidate{
field: StructField{
Key: key,
Index: index,
OmitEmpty: omitEmpty,
Field: field,
decodeType: decodeType(field),
},
named: named,
})
}
}
}
return dominantFields(candidates)
}
// dominantFields drops the candidates hidden by others with the same key and sorts the rest in field order.
func dominantFields(candidates []fieldCandidate) []StructField {
byKey := map[string][]fieldCandidate{}
for _, candidate := range candidates {
byKey[candidate.field.Key] = append(byKey[candidate.field.Key], candidate)
}
fields := []StructField{}
for _, sameKey := range byKey {
if dominant, ok := dominantField(sameKey); ok {
fields = append(fields, dominant)
}
}
sort.Slice(fields, func(i, j int) bool {
return lessIndex(fields[i].Index, fields[j].Index)
})
return fields
}
// dominantField returns the field that wins between candidates with the same key.
// ok is false if there is no single winner.
func dominantField(candidates []fieldCandidate) (StructField, bool) {
depth := len(candidates[0].field.Index)
for _, candidate := range candidates {
depth = min(depth, len(candidate.field.Index))
}
var dominant *fieldCandidate
count, namedCount := 0, 0
for i := range candidates {
if len(candidates[i].field.Index) != depth {
continue
}
count++
if candidates[i].named {
namedCount++
dominant = &candidates[i]
} else if dominant == nil || !dominant.named {
dominant = &candidates[i]
}
}
if count == 1 || namedCount == 1 {
return dominant.field, true
}
return StructField{}, false
}
func lessIndex(a, b []int) bool {
for i := 0; i < len(a) && i < len(b); i++ {
if a[i] != b[i] {
return a[i] < b[i]
}
}
return len(a) < len(b)
}
// isModelField reports if the field is part of the JsonMap of its struct (or promotes fields to it).
func isModelField(field reflect.StructField) bool {
if field.Anonymous {
fieldType := field.Type
if !field.IsExported() {
// Fields of an unexported embedded struct are promoted, but a nil pointer to it can not be set.
if fieldType.Kind() == reflect.Ptr || fieldType.Kind() != reflect.Struct {
return false
}
}
} else if !field.IsExported() {
return false
}
if tag, ok := field.Tag.Lookup("json"); ok {
return tag != "-"
}
return field.Tag.Get("yaml") != "-"
}
// hasTagName reports if the tag the key is resolved from (see FieldKey) has a name.
func hasTagName(field reflect.StructField) bool {
tag := field.Tag.Get("json")
if len(tag) == 0 {
tag = field.Tag.Get("yaml")
}
name, _, _ := strings.Cut(tag, ",")
return name != "" && name != "-"
}
var (
timeType = reflect.TypeOf(time.Time{})
jsonUnmarshalerType = reflect.TypeOf((*json.Unmarshaler)(nil)).Elem()
jsonUnmarshalFromType = reflect.TypeOf((*json.UnmarshalerFrom)(nil)).Elem()
)
// decodeType returns the type used to write the field with encoding/json, or nil if it is written by AnyToType.
// See needsJSONDecode.
func decodeType(field reflect.StructField) reflect.Type {
if !needsJSONDecode(field) {
return nil
}
_, options, _ := strings.Cut(field.Tag.Get("json"), ",")
tag := `json:"V`
if options != "" {
tag += "," + options
}
tag += `"`
return reflect.StructOf([]reflect.StructField{{Name: "V", Type: field.Type, Tag: reflect.StructTag(tag)}})
}
// needsJSONDecode reports if the field has to be written by encoding/json, because its type has an own
// UnmarshalJSON (or UnmarshalJSONFrom) or its json tag has the options `string` or `format:`.
// time.Time is written by AnyToType, which also accepts unix timestamps.
func needsJSONDecode(field reflect.StructField) bool {
fieldType := field.Type
if fieldType == timeType || (fieldType.Kind() == reflect.Ptr && fieldType.Elem() == timeType) {
return false
}
for _, t := range []reflect.Type{fieldType, reflect.PointerTo(fieldType)} {
if t.Implements(jsonUnmarshalerType) || t.Implements(jsonUnmarshalFromType) {
return true
}
}
_, options, _ := strings.Cut(field.Tag.Get("json"), ",")
for options != "" {
var option string
option, options, _ = strings.Cut(options, ",")
if option == "string" || strings.HasPrefix(option, "format:") {
return true
}
}
return false
}
// fieldForRead returns the field of the index path in the struct value.
// ok is false if an embedded pointer on the path is nil, so the field does not exist.
func fieldForRead(structValue reflect.Value, index []int) (reflect.Value, bool) {
value := structValue
for i, fieldIndex := range index {
if i > 0 && value.Kind() == reflect.Ptr {
if value.IsNil() {
return reflect.Value{}, false
}
value = value.Elem()
}
value = value.Field(fieldIndex)
}
return value, true
}
// fieldForWrite returns the field of the index path in the struct value, nil embedded pointers on the path are set.
func fieldForWrite(structValue reflect.Value, index []int) reflect.Value {
value := structValue
for i, fieldIndex := range index {
if i > 0 && value.Kind() == reflect.Ptr {
if value.IsNil() {
value.Set(reflect.New(value.Type().Elem()))
}
value = value.Elem()
}
value = value.Field(fieldIndex)
}
return value
}
package helper
import (
"fmt"
"regexp"
"strconv"
"time"
)
// UnixStringToTime converts a Unix timestamp string to a time.Time object.
// It checks if the string is a valid Unix timestamp and parses it.
func UnixStringToTime(in string) (time.Time, error) {
// Unix seconds date string
match, _ := regexp.MatchString("^[0-9]{1,}$", in)
if !match {
return time.Time{}, fmt.Errorf("invalid unix time: %v", in)
}
seconds, err := strconv.ParseInt(in, 10, 64)
if err != nil {
return time.Time{}, fmt.Errorf("error parsing unix string to time: %v", err)
}
return time.Unix(seconds, 0).UTC(), nil
}
// ISO8601StringToTime converts an ISO8601 date string to a time.Time object.
// It supports RFC3339 format timestamps including timezone offsets,
// as well as database formats without timezone information.
func ISO8601StringToTime(in string) (time.Time, error) {
// RFC3339Nano handles all formats with timezone (Z or +/-HH:MM) including nanoseconds
// Examples: 2026-01-19T14:37:45.673212+01:00, 2026-01-19T14:37:45.123Z, 2026-01-19T14:37:45Z
if date, err := time.Parse(time.RFC3339Nano, in); err == nil {
return date, nil
}
if date, err := time.Parse(time.RFC3339, in); err == nil {
return date, nil
}
// Database formats without timezone - local time only
layout := ""
switch len(in) {
case 26: // yyyy-MM-ddTHH:mm:ss.mmmuuu (microseconds)
layout = "2006-01-02T15:04:05.000000"
case 23: // yyyy-MM-ddTHH:mm:ss.mmm (milliseconds)
layout = "2006-01-02T15:04:05.000"
default:
return time.Time{}, fmt.Errorf("error parsing iso8601 string to time: unsupported format")
}
date, err := time.Parse(layout, in)
if err != nil {
return time.Time{}, fmt.Errorf("error parsing iso8601 string to time: %v", err)
}
return date, nil
}
package helper
import (
"encoding/json/v2"
"fmt"
"io"
"mime"
"net/http"
"net/url"
"slices"
"strings"
"go.yaml.in/yaml/v3"
)
// MultipartMaxSize is the maximum size of a multipart form body that is read by UnmapRequestToJsonMap.
// The whole form is kept in memory, so no temporary files are written. To read a larger form
// (eg. with files), call request.ParseMultipartForm before, the form is not parsed again then.
const MultipartMaxSize = 32 << 20
// UnmarshalRequestToJsonMap unmarshals the json body of the request into a JsonMap.
// An error while reading the body (eg. *http.MaxBytesError) is wrapped.
func UnmarshalRequestToJsonMap(request *http.Request) (map[string]any, error) {
bodyBytes, err := readRequestBody(request)
if err != nil {
return nil, err
}
return UnmarshalJsonToJsonMap(bodyBytes)
}
// UnmarshalYamlRequestToJsonMap unmarshals the yaml body of the request into a JsonMap, see UnmarshalYamlToJsonMap.
// An error while reading the body (eg. *http.MaxBytesError) is wrapped.
func UnmarshalYamlRequestToJsonMap(request *http.Request) (map[string]any, error) {
bodyBytes, err := readRequestBody(request)
if err != nil {
return nil, err
}
return UnmarshalYamlToJsonMap(bodyBytes)
}
func readRequestBody(request *http.Request) ([]byte, error) {
if request == nil {
return nil, fmt.Errorf("request is nil")
}
if request.Body == nil {
return nil, nil
}
defer request.Body.Close()
bodyBytes, err := io.ReadAll(request.Body)
if err != nil {
return nil, fmt.Errorf("error reading request body: %w", err)
}
return bodyBytes, nil
}
// UnmapRequestToJsonMap unmaps the form values of the request (the query and,
// for a url encoded or multipart form, the body) into a JsonMap. Files of a multipart form are ignored.
// A multipart form is limited to MultipartMaxSize, a url encoded form to 10 MiB (by net/http).
// An error while reading the body (eg. *http.MaxBytesError) is wrapped.
func UnmapRequestToJsonMap(request *http.Request) (map[string]any, error) {
if request == nil {
return nil, fmt.Errorf("request is nil")
}
var err error
if IsMediaType(request, "multipart/form-data") {
if request.MultipartForm == nil && request.Body != nil {
request.Body = http.MaxBytesReader(nil, request.Body, MultipartMaxSize)
}
// gosec reports every ParseMultipartForm, the body is limited by http.MaxBytesReader above
// (or the form was already parsed by the caller).
err = request.ParseMultipartForm(MultipartMaxSize) // #nosec G120
} else {
err = request.ParseForm()
}
if err != nil {
return nil, fmt.Errorf("error parsing form: %w", err)
}
return UnmapUrlValuesToJsonMap(request.Form)
}
// MediaType returns the media type of the Content-Type header of the request without parameters
// (eg. `application/json` for `application/json; charset=utf-8`). It is empty if there is no Content-Type.
func MediaType(request *http.Request) (string, error) {
contentType := request.Header.Get("Content-Type")
if contentType == "" {
return "", nil
}
mediaType, _, err := mime.ParseMediaType(contentType)
if err != nil {
return "", fmt.Errorf("invalid Content-Type %q: %v", contentType, err)
}
return mediaType, nil
}
// IsMediaType reports if the Content-Type of the request is one of the given media types.
func IsMediaType(request *http.Request, mediaTypes ...string) bool {
mediaType, err := MediaType(request)
return err == nil && slices.Contains(mediaTypes, mediaType)
}
func UnmarshalJsonToJsonMap(jsonInput []byte) (map[string]any, error) {
mapOut := map[string]any{}
err := json.Unmarshal(jsonInput, &mapOut)
if err != nil {
return nil, fmt.Errorf("error unmarshaling: %v", err)
}
return mapOut, nil
}
// UnmarshalYamlToJsonMap unmarshals yaml into a JsonMap.
// Nested maps with non-string keys are converted to map[string]any, so the result
// has the same shape as an unmarshaled json object. An empty document results in an empty map.
func UnmarshalYamlToJsonMap(yamlInput []byte) (map[string]any, error) {
var out any
err := yaml.Unmarshal(yamlInput, &out)
if err != nil {
return nil, fmt.Errorf("error unmarshaling yaml: %v", err)
}
if out == nil {
return map[string]any{}, nil
}
mapOut, ok := normalizeYamlValue(out).(map[string]any)
if !ok {
return nil, fmt.Errorf("error unmarshaling yaml: top level has to be a mapping, was %T", out)
}
return mapOut, nil
}
// normalizeYamlValue recursively converts map[any]any (yaml mappings with non-string keys) to map[string]any.
func normalizeYamlValue(in any) any {
switch v := in.(type) {
case map[string]any:
for key, value := range v {
v[key] = normalizeYamlValue(value)
}
return v
case map[any]any:
mapOut := make(map[string]any, len(v))
for key, value := range v {
mapOut[fmt.Sprint(key)] = normalizeYamlValue(value)
}
return mapOut
case []any:
for i, value := range v {
v[i] = normalizeYamlValue(value)
}
return v
default:
return in
}
}
func UnmapUrlValuesToJsonMap(values url.Values) (map[string]any, error) {
mapOut := map[string]any{}
for k := range values {
if len(values[k]) > 1 {
arrayOut := []any{}
for _, v := range values[k] {
var unmarshalled any
err := json.Unmarshal([]byte(v), &unmarshalled)
if err == nil {
arrayOut = append(arrayOut, unmarshalled)
} else {
arrayOut = append(arrayOut, v)
}
}
if strings.Contains(k, ".") {
setNestedDotValue(mapOut, strings.Split(k, "."), arrayOut)
} else {
mapOut[k] = arrayOut
}
} else {
value := values.Get(k)
var unmarshalled any
var valToSet any
err := json.Unmarshal([]byte(value), &unmarshalled)
if err == nil {
valToSet = unmarshalled
} else {
valToSet = value
}
if strings.Contains(k, ".") {
setNestedDotValue(mapOut, strings.Split(k, "."), valToSet)
} else {
mapOut[k] = valToSet
}
}
}
return mapOut, nil
}
func setNestedDotValue(m map[string]any, keys []string, value any) {
if len(keys) == 0 {
return
}
if len(keys) == 1 {
m[keys[0]] = value
return
}
key := keys[0]
if existing, ok := m[key]; ok {
if nestedMap, ok := existing.(map[string]any); ok {
setNestedDotValue(nestedMap, keys[1:], value)
return
}
}
nestedMap := make(map[string]any)
m[key] = nestedMap
setNestedDotValue(nestedMap, keys[1:], value)
}
package model
import (
"fmt"
"strings"
)
// ConditionType is the type for all available condition types.
type ConditionType string
// Available condition types.
const (
NONE ConditionType = "-"
EQUAL ConditionType = "equ"
NOT_EQUAL ConditionType = "neq"
MIN_VALUE ConditionType = "min"
MAX_VALUE ConditionType = "max"
CONTAINS ConditionType = "con"
NOT_CONTAINS ConditionType = "nco"
FROM ConditionType = "frm"
NOT_FROM ConditionType = "nfr"
REGX ConditionType = "rex"
FUNC ConditionType = "fun"
DEF ConditionType = "def"
IS_TYPE ConditionType = "ist"
CORRECT_MIN ConditionType = "cmn"
CORRECT_MAX ConditionType = "cmx"
RELATION ConditionType = "rel"
UNIQUE ConditionType = "unq"
)
var ValidConditionTypes = map[ConditionType]int{
NONE: 0,
EQUAL: 1,
NOT_EQUAL: 2,
MIN_VALUE: 3,
MAX_VALUE: 4,
CONTAINS: 5,
NOT_CONTAINS: 6,
FROM: 7,
NOT_FROM: 8,
REGX: 9,
DEF: 10,
IS_TYPE: 11,
CORRECT_MIN: 12,
CORRECT_MAX: 13,
FUNC: 14,
RELATION: 15,
UNIQUE: 16,
}
// ValidIsTypes holds the types that can be checked with `ist` (eg. `istuuid`).
var ValidIsTypes = map[string]struct{}{
"uuid": {},
"unixmilli": {},
"timerfc3339": {},
"email": {},
"url": {},
"alpha": {},
"alphanum": {},
"numeric": {},
"hex": {},
"base64": {},
"json": {},
"jwt": {},
"ip": {},
"ipv4": {},
"ipv6": {},
"mac": {},
"password": {},
}
// IsRequirement reports if the condition type is an actual check (not none or default).
func (c ConditionType) IsRequirement() bool {
return c != NONE && c != DEF
}
// IsCorrect reports if the condition type checks the number of correct inner fields.
func (c ConditionType) IsCorrect() bool {
return c == CORRECT_MIN || c == CORRECT_MAX
}
// LookupConditionType checks our validConditionType map for the scanned condition type.
// If not found, an error is returned.
func LookupConditionType(conType ConditionType) error {
if _, ok := ValidConditionTypes[conType]; ok {
return nil
}
return fmt.Errorf("expected a valid condition type, found: %s", conType)
}
// GetConditionType returns the condition type from a string.
// It checks if the string starts with a valid condition type prefix.
// If the string is not valid, an error is returned.
func GetConditionType(s string) (ConditionType, error) {
var conditionType ConditionType
if len(s) > 3 {
conditionType = ConditionType(s[:3])
} else {
conditionType = ConditionType(s)
}
if _, ok := ValidConditionTypes[conditionType]; !ok {
return conditionType, fmt.Errorf("invalid condition type: %s", conditionType)
}
return conditionType, nil
}
// GetConditionByType extracts the condition value from a string based on the condition type.
// It trims the prefix of the condition type from the string and returns the remaining part.
// If the condition type is not valid or the value is empty, an error is returned.
func GetConditionByType(conditionFull string, conditionType ConditionType) (string, error) {
if len(conditionType) != 3 {
return "", fmt.Errorf("length of conditionType has to be 3: %s", conditionType)
}
condition := strings.TrimPrefix(conditionFull, string(conditionType))
if len(condition) == 0 {
return "", fmt.Errorf("empty %s value", conditionType)
}
return condition, nil
}
package model
import (
"errors"
"strings"
)
var (
// ErrInvalidRequirement is returned (wrapped) for a requirement that can never be validated.
// The validations of a struct are checked on extraction (on the first call for a struct type), eg. a requirement
// that can not be parsed, an invalid group, `equ` with a value that is not a number on an int field
// or `cmn` on a field that is not a struct. While validating it is returned for an unknown function (`fun`),
// an unknown condition type or `rel` or `$` used without the other fields (eg. in validator.ValidateValueWithParser).
// It is a mistake in the code, not in the input, so a handler can answer it with 500.
ErrInvalidRequirement = errors.New("invalid requirement")
// ErrUnsupportedMediaType is returned by validator.UnpackAndValidate (wrapped) if the Content-Type of the request
// is not supported. A handler can answer it with 415.
ErrUnsupportedMediaType = errors.New("unsupported media type")
// ErrMalformedInput is returned by all unpack functions (wrapped) if the input can not be read or parsed,
// eg. invalid json or yaml, an invalid query or a body that is larger than allowed by http.MaxBytesReader
// (the *http.MaxBytesError is wrapped too). A handler can answer it with 400 (or 413).
ErrMalformedInput = errors.New("malformed input")
)
// FieldErrors holds the errors of all invalid fields of a validation.
// All errors that are not one of the sentinel errors above are errors of the validation.
type FieldErrors []error
// Error joins the messages of all field errors.
func (e FieldErrors) Error() string {
messages := make([]string, len(e))
for i, err := range e {
messages[i] = err.Error()
}
return strings.Join(messages, ", ")
}
// Unwrap returns the single field errors, so errors.Is and errors.As work on them.
func (e FieldErrors) Unwrap() []error {
return e
}
package model
import (
"fmt"
"strings"
)
// FieldRef is the parsed path to another field, used by `rel` conditions and `$` references.
// The path is relative to the level of the validated field: `name` is a field on the same level,
// `../name` is a field one level up (repeatable) and `/name` is a field of the top level.
// Inner fields are reached with `.` (eg. `ports.port`), on a list this collects the field of every item.
//
// `${name}` is not a field, but a value injected with [validator.Inject] for a single validation call.
// Then Injected is set and Path holds only the name.
type FieldRef struct {
Raw string
Root bool
Up int
Path []string
Injected bool
}
// ParseFieldRef parses a field path like `name`, `../name`, `/ports.port` or an injected value like `${name}`.
func ParseFieldRef(raw string) (*FieldRef, error) {
if strings.HasPrefix(raw, "${") {
name, ok := strings.CutSuffix(raw[2:], "}")
if !ok || name == "" || strings.ContainsAny(name, "{}") {
return nil, fmt.Errorf("invalid injected value %q, expected ${name}", raw)
}
return &FieldRef{Raw: raw, Path: []string{name}, Injected: true}, nil
}
ref := &FieldRef{Raw: raw}
s := raw
if strings.HasPrefix(s, "/") {
ref.Root = true
s = s[1:]
}
for strings.HasPrefix(s, "../") {
if ref.Root {
return nil, fmt.Errorf("invalid field path %q, `/` and `../` can not be combined", raw)
}
ref.Up++
s = s[3:]
}
if s == "" {
return nil, fmt.Errorf("invalid field path %q, field name missing", raw)
}
ref.Path = strings.Split(s, ".")
for _, segment := range ref.Path {
if segment == "" || segment == ".." {
return nil, fmt.Errorf("invalid field path %q", raw)
}
}
return ref, nil
}
package model
import (
"fmt"
"strings"
)
// Group represents a validation group with a name, condition type, and condition value.
// The name is expected to start with "gr" followed by a condition type and value.
// The condition type is validated against known condition types, allowed are min and max.
// The condition value is extracted based on the condition type.
type Group struct {
Name string
ConditionType ConditionType
ConditionValue string
}
// GetGroups parses a string to extract validation groups.
// It splits the string by spaces and creates a Group for each part.
// Each group must start with "gr" and can have a condition type and value.
// If the group name is invalid or the condition type is not recognized, an error is returned.
func GetGroups(s string) ([]*Group, error) {
groups := []*Group{}
groupsString := strings.Split(s, " ")
for _, g := range groupsString {
group := &Group{}
var groupCondition string
if len(g) > 3 {
group.Name = g[:3]
groupCondition = g[3:]
} else {
return nil, fmt.Errorf("group too short: %s", group.Name)
}
if !strings.HasPrefix(group.Name, "gr") {
return nil, fmt.Errorf("invalid group name: %s", group.Name)
}
var err error
group.ConditionType, err = GetConditionType(groupCondition)
if err != nil {
return nil, err
}
group.ConditionValue, err = GetConditionByType(groupCondition, group.ConditionType)
if err != nil {
return nil, err
}
groups = append(groups, group)
}
return groups, nil
}
package model
import (
"fmt"
"regexp"
"strings"
)
// RootNode is what starts every parsed AST (=abstract syntax tree).
type RootNode struct {
RootValue *AstValue
}
// ExtractDefault searches the AST for a 'DEF' condition and returns its value.
func (r *RootNode) ExtractDefault() string {
if r.RootValue == nil {
return ""
}
return r.RootValue.ExtractDefault()
}
// AstValue (=abstract syntax tree value) holds a Type ("Condition" or "Group") as well as a `ConditionType` and `ConditionValue`.
// The ConditionType is a [model.ConditionType] and the ConditionValue is any string (numbers are also represented as string).
//
// A `rel` condition holds the path of the related field in Ref and the conditions
// for the related field in ConditionGroup. A condition with a `$` value (eg. `min$min_replicas`
// or the injected value `equ${api_key}`) holds the path of the referenced field in Ref,
// its value is resolved while validating.
//
// The AST is cached and shared between goroutines, it must not be modified while validating.
type AstValue struct {
Type AstValueType
ConditionType ConditionType
ConditionValue string
ConditionGroup ConditionGroup
Operator Operator
Start int
End int
// Ref is the path of the related (`rel`) or referenced (`$`) field.
Ref *FieldRef
// Regex is the compiled regular expression of a `rex` condition with a fixed value.
Regex *regexp.Regexp
// List is the split value of a `frm` or `nfr` condition with a fixed value.
List []string
// Number is the parsed value of a `min` or `max` condition, if HasNumber is set.
Number float64
HasNumber bool
// UsesFields reports if the AST contains a `rel` condition or a `$` reference.
// It is only set on the root value by the parser.
UsesFields bool
}
// HasFieldUsage recursively checks if the AST value contains a `rel` condition or a `$` reference.
func (r *AstValue) HasFieldUsage() bool {
if r == nil {
return false
}
for _, v := range r.ConditionGroup {
if v.Ref != nil {
return true
}
if v.Type == GROUP && v.HasFieldUsage() {
return true
}
}
return false
}
// ExtractDefault recursively searches the AST value for a 'DEF' condition and returns its value.
func (r *AstValue) ExtractDefault() string {
for _, v := range r.ConditionGroup {
if v.Type == CONDITION && v.ConditionType == DEF {
return v.ConditionValue
}
if v.Type == GROUP {
if def := v.ExtractDefault(); def != "" {
return def
}
}
}
return ""
}
// HasCondition recursively checks if the AST value contains a condition for which [match] returns true.
func (r *AstValue) HasCondition(match func(ConditionType) bool) bool {
if r == nil {
return false
}
for _, v := range r.ConditionGroup {
if v.Type == CONDITION && match(v.ConditionType) {
return true
}
if v.Type == GROUP && v.HasCondition(match) {
return true
}
}
return false
}
// AstValueType is the type for all available AST value types.
type AstValueType string
const (
EMPTY AstValueType = "Empty"
GROUP AstValueType = "Group"
CONDITION AstValueType = "Condition"
)
// ConditionGroup is a slice of AstValue pointers.
type ConditionGroup []*AstValue
// AstGroupToString converts the AstValue's ConditionGroup to a string representation.
// It iterates over each AstValue in the group and formats it based on its type.
// If the AstValue is a group, it recursively calls itself to get the string representation of the group.
// If the AstValue is a condition, it formats it as a string with its ConditionType and ConditionValue.
// The resulting string is a concatenation of all conditions and groups, separated by spaces.
func (r AstValue) AstGroupToString() string {
groupConditions := []string{}
groupString := ""
for _, v := range r.ConditionGroup {
switch v.Type {
case GROUP:
if len(v.Operator) > 0 {
groupConditions = append(groupConditions, fmt.Sprintf("(%v) %v", v.AstGroupToString(), v.Operator))
} else {
groupConditions = append(groupConditions, fmt.Sprintf("(%v)", v.AstGroupToString()))
}
case CONDITION:
groupConditions = append(groupConditions, v.AstConditionToString())
}
}
groupString = strings.Join(groupConditions, " ")
return groupString
}
// AstConditionToString converts the AstValue's ConditionType and ConditionValue to a string representation.
// If the AstValue has an Operator, it includes that in the string.
// The resulting string is formatted as "<ConditionType>'<ConditionValue>' <Operator>" if the Operator is present,
// or as "<ConditionType>'<ConditionValue>'" if the Operator is not present.
// A `rel` condition is formatted as "rel(<path> <conditions>)", a `$` reference as "<ConditionType>$<path>"
// and an injected value as "<ConditionType>${<name>}".
func (r AstValue) AstConditionToString() string {
var condition string
switch {
case r.ConditionType == RELATION && r.Ref != nil:
condition = fmt.Sprintf("rel(%v %v)", r.Ref.Raw, r.AstGroupToString())
case r.Ref != nil && r.Ref.Injected:
condition = fmt.Sprintf("%v%v", r.ConditionType, r.Ref.Raw)
case r.Ref != nil:
condition = fmt.Sprintf("%v$%v", r.ConditionType, r.Ref.Raw)
default:
condition = fmt.Sprintf("%v'%v'", r.ConditionType, r.ConditionValue)
}
if len(r.Operator) > 0 {
return condition + " " + string(r.Operator)
}
return condition
}
// Operator is the type for all available operators.
type Operator string
// Available operators.
const (
// Group states
AND Operator = "&&"
OR Operator = "||"
IMPLIES Operator = "=>"
)
// validOperator is a map that holds valid operators and their corresponding integer values.
// This map is used to validate operators in the AST.
var validOperator = map[Operator]int{
AND: 0,
OR: 1,
IMPLIES: 2,
}
// LookupOperator checks our validOperator map for the scanned operator.
// If not found, an error is returned.
func LookupOperator(operator Operator) error {
if _, ok := validOperator[operator]; ok {
return nil
}
return fmt.Errorf("expected a valid operator, found: %s", operator)
}
package model
// Default tag type.
const VLD string = "vld"
// Validation represents a validation rule for a struct field.
type Validation struct {
Key string
Type ValidatorType
Requirement string
Groups []*Group
Default string
OmitEmpty bool
// InnerValidation holds the validations of the inner fields of a struct field or of the items of a list of structs.
// If it is nil (and InnerValidationRef too), the value is not validated inside, but taken as it is
// (eg. for a struct without any tag). If it is empty, all inner fields are left out.
InnerValidation []Validation
// InnerValidationRef is set by GetValidationsFromStruct instead of InnerValidation for a field
// whose type refers back to a struct that contains it (eg. `Children []Node` in Node).
// It points to the validations of that struct, so recursive types do not need endless validations.
InnerValidationRef *[]Validation
// Parsed AST representation of the requirement to avoid redundant parsing
RequirementAST *AstValue
// NoFieldUsage is set by GetValidationsFromStruct if neither the requirement nor any inner validation
// uses `rel` or a `$` reference. The validator then skips tracking the levels of the input.
// It is false for validations built by hand, which is always correct, just a bit slower.
NoFieldUsage bool
}
// UsesFields reports if the validation (or one of its inner validations) may use `rel` or a `$` reference.
func (v *Validation) UsesFields() bool {
return !v.NoFieldUsage
}
// Inner returns the inner validations of a struct field or of the items of a list of structs.
func (v *Validation) Inner() []Validation {
if v.InnerValidationRef != nil {
return *v.InnerValidationRef
}
return v.InnerValidation
}
// ValidatorMap is a map of validation keys to Validation objects.
// It is used to store and manage multiple validation rules for different struct fields.
type ValidatorMap map[string]Validation
package model
import (
"encoding"
"reflect"
)
var textUnmarshalerType = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem()
// ValidatorType is the type for all available validation types.
type ValidatorType string
const (
String ValidatorType = "string"
Int ValidatorType = "int"
Float ValidatorType = "float"
Bool ValidatorType = "bool"
Array ValidatorType = "array"
Map ValidatorType = "map"
Struct ValidatorType = "struct"
)
func (v ValidatorType) ToReflectType() reflect.Type {
switch v {
case String:
return reflect.TypeOf("")
case Int:
return reflect.TypeOf(int(0))
case Float:
return reflect.TypeOf(float64(0))
case Bool:
return reflect.TypeOf(false)
case Array:
return reflect.TypeOf([]string{})
case Map:
return reflect.TypeOf(map[string]string{})
case Struct:
return reflect.TypeOf(struct{}{})
default:
return reflect.TypeOf(struct{}{})
}
}
// ReflectTypeToValidatorType determines the ValidatorType based on the reflect.Type of a struct field.
// Non-struct types that can be unmarshaled from text (e.g. uuid.UUID or net.IP) are validated as String,
// pointers are dereferenced for that check. Structs like time.Time keep their Struct type.
// All other types are handled by ReflectKindToValidatorType.
func ReflectTypeToValidatorType(reflectType reflect.Type) ValidatorType {
elemType := reflectType
if elemType.Kind() == reflect.Ptr {
elemType = elemType.Elem()
}
if elemType.Kind() != reflect.Struct && reflect.PointerTo(elemType).Implements(textUnmarshalerType) {
return String
}
return ReflectKindToValidatorType(reflectType.Kind())
}
// TypeFromInterface determines the ValidatorType based on the type of the input interface.
// It checks the type of the input and returns the corresponding ValidatorType.
// If the type is not recognized, it defaults to Struct.
// It handles basic types like string, int, float, bool, and complex types like JsonMap and arrays.
// It also checks for time.Time type and returns the appropriate ValidatorType.
func ReflectKindToValidatorType(reflectType reflect.Kind) ValidatorType {
switch reflectType {
case reflect.String:
return String
case reflect.Int, reflect.Int64, reflect.Int32, reflect.Int16, reflect.Int8:
return Int
case reflect.Float64, reflect.Float32:
return Float
case reflect.Bool:
return Bool
case reflect.Map:
return Map
case reflect.Slice, reflect.Array:
return Array
case reflect.Struct:
return Struct
default:
return Struct
}
}
package parser
import (
"strings"
"github.com/siherrmann/validator/model"
)
// Lexer performs lexical analysis/scanning of the JSON
type Lexer struct {
// Input is kept as a string, not []byte or []rune: every delimiter the lexer
// switches on below ('(', ')', '|', '&', '\'', whitespace, and isLetter's a-z) is
// ASCII, and no ASCII byte can appear inside a multi-byte UTF-8 sequence. That
// means byte indexing is always safe here, and slicing a string (l.Input[a:b])
// shares the original backing array instead of allocating, unlike string(runes).
Input string
char byte // current char under examination
lastTokenType model.TokenType // last TokenType for splitting condition type from value.
relPending bool // last token was the condition type `rel`, a `(` is expected.
pathNext bool // last tokens were `rel(`, the next token is a field path.
position int // current position in input (points to current char)
nextPosition int // current reading position in input (after current char)
line int // line number for better error reporting, etc
}
// NewLexer creates and returns a pointer to the Lexer
func NewLexer(input string) *Lexer {
l := &Lexer{Input: input}
l.readChar()
return l
}
func (l *Lexer) readChar() {
if l.nextPosition >= len(l.Input) {
// End of input (haven't read anything yet or EOF)
// 0 is ASCII code for "NUL" character
l.char = 0
} else {
l.char = l.Input[l.nextPosition]
}
l.position = l.nextPosition
l.nextPosition++
}
// NextToken switches through the lexer's current char and creates a new model.
// It then it calls readChar to advance the lexer and it returns the token.
func (l *Lexer) NextToken() model.Token {
var t model.Token
skipped := l.skipWhitespace()
// `rel(` is followed by a field path instead of a condition type.
relPending, pathNext := l.relPending, l.pathNext
l.relPending, l.pathNext = false, false
// A value directly after the condition type can start with `-` or `(` (eg. `min-5` or `rex(a|b)$`).
if (l.char == '-' || l.char == '(') && !skipped && !relPending && l.lastTokenType == model.LexerConditionType {
return l.conditionValueToken()
}
if pathNext && l.char != 0 && l.char != '(' && l.char != ')' {
t.Literal = l.readFieldPath()
t.Line = l.line
t.Start = l.position
t.End = l.position
t.Type = model.LexerFieldPath
l.lastTokenType = model.LexerFieldPath
return t
}
switch l.char {
case '-':
t = newToken(model.LexerEmptyRequirement, l.line, l.position, l.position+1, l.Input[l.position:l.position+1])
case '(':
t = newToken(model.LexerLeftBrace, l.line, l.position, l.position+1, l.Input[l.position:l.position+1])
l.pathNext = relPending
case ')':
t = newToken(model.LexerRightBrace, l.line, l.position, l.position+1, l.Input[l.position:l.position+1])
case '|', '&', '=':
t.Literal = l.readOperator()
t.Line = l.line
t.Start = l.position
t.End = l.position + 2
t.Type = model.LexerOperator
l.lastTokenType = model.LexerOperator
// readOperator already moved behind the operator.
return t
case '\'':
t.Literal = l.readString()
t.Line = l.line
t.Start = l.position
t.End = l.position + 1
t.Type = model.LexerConditionValueString
l.lastTokenType = model.LexerConditionValueString
case 0:
t.Literal = ""
t.Line = l.line
t.Type = model.LexerEOF
l.lastTokenType = model.LexerEOF
default:
if l.lastTokenType == model.LexerConditionType {
return l.conditionValueToken()
} else if isLetter(l.char) {
t.Literal = l.readConditionType()
t.Line = l.line
t.Start = l.position
t.End = l.position
t.Type = model.LexerConditionType
l.lastTokenType = model.LexerConditionType
l.relPending = t.Literal == string(model.RELATION)
return t
}
t = newToken(model.LexerIllegal, l.line, l.position, l.position, l.Input[l.position:l.position+1])
}
l.readChar()
return t
}
// conditionValueToken reads a condition value token.
func (l *Lexer) conditionValueToken() model.Token {
t := model.Token{Literal: l.readConditionValue(), Line: l.line, Start: l.position, End: l.position, Type: model.LexerConditionValue}
l.lastTokenType = model.LexerConditionValue
return t
}
// skipWhitespace skips whitespace and reports if there was any.
func (l *Lexer) skipWhitespace() bool {
skipped := false
for l.char == ' ' || l.char == '\t' || l.char == '\n' || l.char == '\r' {
if l.char == '\n' {
l.line++
}
l.readChar()
skipped = true
}
return skipped
}
// newToken builds a single-character token. literal is sliced by the caller from
// l.Input rather than built with string(char) — a substring of an existing string
// shares its backing array and costs no allocation, while converting a rune (or byte)
// to a string always allocates a new one.
func newToken(tokenType model.TokenType, line, start, end int, literal string) model.Token {
return model.Token{
Type: tokenType,
Literal: literal,
Line: line,
Start: start,
End: end,
}
}
func isLetter(char byte) bool {
return 'a' <= char && char <= 'z'
}
func isOperator(char byte) bool {
return char == '|' || char == '&' || char == '=' || char == '>'
}
// readOperator sets a start position and reads through two characters to get a full operator
func (l *Lexer) readOperator() string {
position := l.position
for isOperator(l.char) && l.position < position+2 {
l.readChar()
}
return l.Input[position:l.position]
}
// readString sets a start position and reads through characters
// until it finds a closing `'`. It stops consuming characters and
// returns the string between the start and end positions.
// The charakter`'` inside the string is escaped with a '/'
// and the '/' is removed after reading the string.
func (l *Lexer) readString() string {
position := l.position + 1
for {
prevChar := l.char
l.readChar()
if (l.char == '\'' && prevChar != '/') || l.char == 0 {
break
}
}
s := l.Input[position:l.position]
// ReplaceAll allocates even when there is nothing to replace, so only pay for it
// when the value actually contains an escaped quote.
if strings.Contains(s, "/'") {
s = strings.ReplaceAll(s, "/'", "'")
}
return s
}
// readConditionType sets a start position and reads through 3 characters
// to get a condition type (unvalidated).
func (l *Lexer) readConditionType() string {
position := l.position
for isLetter(l.char) && l.position < position+3 {
l.readChar()
}
return l.Input[position:l.position]
}
// readConditionValue sets a start position and reads through characters
// until any kind of whitespace or a closing brace to get a condition value (unvalidated).
// Braces opened in the value are part of it (eg. `rex^(a|b)+$`), so only a `)` without
// an opening `(` in the value ends it, which is the closing brace of a group.
func (l *Lexer) readConditionValue() string {
position := l.position
depth := 0
for {
switch l.char {
case ' ', '\t', '\n', '\r', 0:
return l.Input[position:l.position]
case '(':
depth++
case ')':
if depth == 0 {
return l.Input[position:l.position]
}
depth--
}
l.readChar()
}
}
// readFieldPath sets a start position and reads through characters
// until any kind of whitespace or a closing brace to get a field path (unvalidated).
func (l *Lexer) readFieldPath() string {
return l.readConditionValue()
}
package parser
import (
"fmt"
"regexp"
"strconv"
"strings"
"github.com/siherrmann/validator/model"
)
// Parser holds a Lexer, errors, the currentToken, and the peekToken (next token).
// Parser methods handle iterating through tokens and building and AST.
type Parser struct {
lexer *Lexer
errors []string
currentToken model.Token
peekToken model.Token
}
// NewParser creates a new Parser instance.
func NewParser() *Parser {
return &Parser{}
}
// ParseValidation parses tokens and creates an AST. It returns the RootNode
// which holds a Value and in it the rest of the tree.
// It creates a new Lexer for reset lexer state and initializes the parser's tokens.
// It returns an error if the parsing fails.
func (p *Parser) ParseValidation(validation string) (model.RootNode, error) {
// nil rather than []string{}: append handles a nil slice fine, and a successful
// parse (the common case) never appends, so it never pays for this allocation.
p.errors = nil
p.lexer = NewLexer(validation)
// Read two tokens, so currentToken and peekToken are both set.
p.nextToken()
p.nextToken()
var rootNode model.RootNode
val := p.parseGroup(true)
if val == nil || len(p.errors) > 0 {
if len(p.errors) == 0 {
p.parseError(fmt.Sprintf("error parsing validation, expected a value, got: %v", p.currentToken.Literal))
}
return model.RootNode{RootValue: &model.AstValue{}}, fmt.Errorf("%w %q: %s", model.ErrInvalidRequirement, validation, p.Errors())
}
val.UsesFields = val.HasFieldUsage()
rootNode.RootValue = val
return rootNode, nil
}
// nextToken sets our current token to the peekToken and the peekToken to
// p.lexer.NextToken() which scans and returns the next token.
func (p *Parser) nextToken() {
p.currentToken = p.peekToken
p.peekToken = p.lexer.NextToken()
}
func (p *Parser) currentTokenTypeIs(t model.TokenType) bool {
return p.currentToken.Type == t
}
// parseGroup is called when an open left brace `(` token is found or a requirement starts without a '('.
func (p *Parser) parseGroup(root bool) *model.AstValue {
return p.parseGroupFrom(root, false)
}
// parseGroupFrom parses a group. With open, the group starts as already opened.
// This is used for the inner conditions of `rel(<path> <conditions>)`,
// where the opening brace and the path are already consumed.
func (p *Parser) parseGroupFrom(root bool, open bool) *model.AstValue {
// Most tags hold only a handful of conditions/sub-groups; sizing the slice up
// front avoids the repeated grow-and-copy an append-from-nil would do. A group
// that turns out to be EMPTY or errors before appending anything just leaves this
// capacity unused, which is cheaper than the reallocations it saves in the common case.
group := &model.AstValue{Type: model.GROUP, ConditionGroup: make(model.ConditionGroup, 0, 4)}
grpState := model.GrpStart
if open {
grpState = model.GrpOpen
group.Start = p.currentToken.Start
}
for !p.currentTokenTypeIs(model.LexerEOF) && grpState != model.GrpEnd {
if len(p.errors) > 0 {
return nil
}
switch grpState {
case model.GrpStart:
if p.currentTokenTypeIs(model.LexerLeftBrace) {
if root {
innerGroup := p.parseGroup(false)
group.ConditionGroup = append(group.ConditionGroup, innerGroup)
grpState = model.GrpOpen
} else {
group.Start = p.currentToken.Start
p.nextToken()
grpState = model.GrpOpen
}
} else if p.currentTokenTypeIs(model.LexerConditionType) {
group.Start = p.currentToken.Start
grpState = model.GrpOpen
} else if p.currentTokenTypeIs(model.LexerEmptyRequirement) {
if root && p.peekToken.Type != model.LexerEOF {
p.parseError(fmt.Sprintf("error parsing validation, `-` can not be combined with other conditions, got: %s", p.peekToken.Literal))
return nil
}
group.Type = model.EMPTY
group.Start = p.currentToken.Start
group.End = p.currentToken.End
grpState = model.GrpEnd
return group
} else {
p.parseError(fmt.Sprintf(
"error parsing validation group, expected left brace, `-` or condition, got: %s",
p.currentToken.Literal,
))
return nil
}
case model.GrpOpen:
if p.currentTokenTypeIs(model.LexerRightBrace) {
if root {
p.parseError("error parsing group, got `)` without an opening `(`")
return nil
} else if len(group.ConditionGroup) == 0 {
p.parseError("error parsing group, expected a condition in `()`")
return nil
} else if !p.lastConditionComplete(group) {
return nil
}
group.End = p.currentToken.End
p.nextToken()
grpState = model.GrpEnd
} else if p.currentTokenTypeIs(model.LexerLeftBrace) {
innerGroup := p.parseGroup(false)
group.ConditionGroup = append(group.ConditionGroup, innerGroup)
if len(group.ConditionGroup) > 1 && len(group.ConditionGroup[len(group.ConditionGroup)-2].Operator) == 0 {
group.ConditionGroup[len(group.ConditionGroup)-2].Operator = model.AND
}
} else if p.currentTokenTypeIs(model.LexerConditionType) {
condition := p.parseCondition()
group.ConditionGroup = append(group.ConditionGroup, condition)
if len(group.ConditionGroup) > 1 && len(group.ConditionGroup[len(group.ConditionGroup)-2].Operator) == 0 {
group.ConditionGroup[len(group.ConditionGroup)-2].Operator = model.AND
}
} else if p.currentTokenTypeIs(model.LexerOperator) && len(group.ConditionGroup) > 0 {
if last := group.ConditionGroup[len(group.ConditionGroup)-1]; len(last.Operator) > 0 {
p.parseError(fmt.Sprintf("error parsing group, expected a condition after %v, got: %s", last.Operator, p.currentToken.Literal))
return nil
}
operator := p.parseOperator()
group.ConditionGroup[len(group.ConditionGroup)-1].Operator = operator
p.nextToken()
} else {
p.parseError(fmt.Sprintf(
"error parsing group, expected right brace, condition or operator, got: %s, type: %v",
p.currentToken.Literal,
p.currentToken.Type,
))
return nil
}
}
}
if p.currentTokenTypeIs(model.LexerEOF) && grpState == model.GrpOpen && !root {
p.parseError("error parsing group, expected `)` at the end of the requirement")
return nil
}
group.End = p.currentToken.Start
if len(p.errors) > 0 || (len(group.ConditionGroup) > 0 && !p.lastConditionComplete(group)) {
return nil
}
if err := normalizeImplication(group); err != nil {
p.parseError(err.Error())
return nil
}
return group
}
// lastConditionComplete reports a parse error if the last value of the group ends with an operator (eg. `min1 &&`).
func (p *Parser) lastConditionComplete(group *model.AstValue) bool {
if last := group.ConditionGroup[len(group.ConditionGroup)-1]; len(last.Operator) > 0 {
p.parseError(fmt.Sprintf("error parsing group, expected a condition after %v", last.Operator))
return false
}
return true
}
// normalizeImplication restructures a group with an implication (`=>`) into exactly two values:
// the premise (everything before the first `=>`, carrying the `=>` operator) and the consequence
// (everything after it). `=>` binds weaker than `&&` and `||` and is right associative,
// so `a && b => c => d` is `(a && b) => (c => d)`. Doing this while parsing keeps the validation
// a single check: if the premise fails, the group is fulfilled.
func normalizeImplication(group *model.AstValue) error {
conditions := group.ConditionGroup
k := -1
for i, v := range conditions {
if v.Operator == model.IMPLIES {
k = i
break
}
}
if k == -1 {
return nil
}
if last := conditions[len(conditions)-1]; len(last.Operator) > 0 {
return fmt.Errorf("error parsing group, expected a condition after %v", last.Operator)
}
premise := conditions[k]
if k > 0 {
inner := conditions[: k+1 : k+1]
inner[k].Operator = ""
premise = &model.AstValue{Type: model.GROUP, ConditionGroup: inner, Operator: model.IMPLIES, Start: inner[0].Start, End: inner[k].End}
}
consequence := conditions[k+1]
if len(conditions)-(k+1) > 1 {
inner := conditions[k+1:]
consequence = &model.AstValue{Type: model.GROUP, ConditionGroup: inner, Start: inner[0].Start, End: inner[len(inner)-1].End}
if err := normalizeImplication(consequence); err != nil {
return err
}
}
group.ConditionGroup = model.ConditionGroup{premise, consequence}
return nil
}
// parseCondition is used to parse a condition and setting the `conditionType`:`condition` pair.
//
// Special cases:
// - `rel(<path> <conditions>)` parses the path of the related field and its conditions as a group.
// - A value starting with `$` (not quoted) is a reference to another field (eg. `min$min_replicas`)
// or to an injected value (eg. `equ${api_key}`).
// - `unq` can be used without a value.
// - Fixed values are prepared once here (see precomputeConditionValue).
func (p *Parser) parseCondition() *model.AstValue {
condition := &model.AstValue{Type: model.CONDITION}
conditionState := model.ConType
for conditionState != model.ConEnd {
switch conditionState {
case model.ConType:
if p.currentTokenTypeIs(model.LexerConditionType) {
condition.Start = p.currentToken.Start
condition.ConditionType = p.parseConditionType()
p.nextToken()
if condition.ConditionType == model.RELATION {
p.parseRelation(condition)
return condition
}
conditionState = model.ConValue
} else {
p.parseError(fmt.Sprintf(
"error parsing condition type, expected CndType token, got: %s",
p.currentToken.Literal,
))
return condition
}
case model.ConValue:
if p.currentTokenTypeIs(model.LexerConditionValue) || p.currentTokenTypeIs(model.LexerConditionValueString) {
condition.ConditionValue = p.parseConditionValue()
if p.currentTokenTypeIs(model.LexerConditionValue) && strings.HasPrefix(condition.ConditionValue, "$") {
p.parseReference(condition)
} else {
p.precomputeConditionValue(condition)
}
condition.End = p.currentToken.End
p.nextToken()
conditionState = model.ConEnd
} else if condition.ConditionType == model.UNIQUE {
// `unq` without a value checks the items themselves.
conditionState = model.ConEnd
} else {
p.parseError(fmt.Sprintf(
"error parsing condition, expected ConValue token, got: %s",
p.currentToken.Literal,
))
return condition
}
}
}
return condition
}
// parseRelation parses `(<path> <conditions>)` after the condition type `rel`.
func (p *Parser) parseRelation(condition *model.AstValue) {
if !p.currentTokenTypeIs(model.LexerLeftBrace) {
p.parseError(fmt.Sprintf("error parsing rel, expected `(`, got: %s", p.currentToken.Literal))
return
}
p.nextToken()
if !p.currentTokenTypeIs(model.LexerFieldPath) {
p.parseError(fmt.Sprintf("error parsing rel, expected a field path, got: %s", p.currentToken.Literal))
return
}
ref, err := model.ParseFieldRef(p.currentToken.Literal)
if err != nil {
p.parseError(fmt.Sprintf("error parsing rel: %v", err))
return
}
condition.Ref = ref
condition.ConditionValue = ref.Raw
p.nextToken()
if p.currentTokenTypeIs(model.LexerRightBrace) {
p.parseError(fmt.Sprintf("error parsing rel, expected conditions for field %s", ref.Raw))
return
}
inner := p.parseGroupFrom(false, true)
if inner == nil {
return
}
condition.ConditionGroup = inner.ConditionGroup
condition.End = inner.End
}
// parseReference parses a `$<path>` or `${<name>}` condition value.
func (p *Parser) parseReference(condition *model.AstValue) {
switch condition.ConditionType {
case model.FUNC, model.DEF, model.IS_TYPE, model.CORRECT_MIN, model.CORRECT_MAX, model.UNIQUE:
p.parseError(fmt.Sprintf("error parsing condition, %v can not reference a field", condition.ConditionType))
return
}
// `$name` is a field (path without the `$`), `${name}` an injected value.
raw := condition.ConditionValue
if !strings.HasPrefix(raw, "${") {
raw = raw[1:]
}
ref, err := model.ParseFieldRef(raw)
if err != nil {
p.parseError(fmt.Sprintf("error parsing reference: %v", err))
return
}
condition.Ref = ref
}
// precomputeConditionValue prepares the fixed value of a condition once while parsing,
// so it does not have to be done on every validation:
// `rex` is compiled, `frm` and `nfr` are split and `min` and `max` are parsed to a number.
// Values that can never be valid are reported as parse error: a `min`, `max`, `cmn` or `cmx`
// value that is not a number, an invalid regex and an unknown `ist` type.
func (p *Parser) precomputeConditionValue(condition *model.AstValue) {
switch condition.ConditionType {
case model.REGX:
regex, err := regexp.Compile(condition.ConditionValue)
if err != nil {
p.parseError(fmt.Sprintf("error parsing regex %s: %v", condition.ConditionValue, err))
return
}
condition.Regex = regex
case model.FROM, model.NOT_FROM:
if strings.TrimSpace(condition.ConditionValue) != "" {
condition.List = strings.Split(condition.ConditionValue, ",")
}
case model.MIN_VALUE, model.MAX_VALUE:
number, err := strconv.ParseFloat(condition.ConditionValue, 64)
if err != nil {
p.parseError(fmt.Sprintf("error parsing condition %v, value %s is not a number", condition.ConditionType, condition.ConditionValue))
return
}
condition.Number = number
condition.HasNumber = true
case model.CORRECT_MIN, model.CORRECT_MAX:
if _, err := strconv.Atoi(condition.ConditionValue); err != nil {
p.parseError(fmt.Sprintf("error parsing condition %v, value %s is not an integer", condition.ConditionType, condition.ConditionValue))
}
case model.IS_TYPE:
if _, ok := model.ValidIsTypes[condition.ConditionValue]; !ok {
p.parseError(fmt.Sprintf("error parsing condition ist, unknown type %s", condition.ConditionValue))
}
}
}
// parseOperator is used to parse the condition type.
func (p *Parser) parseOperator() model.Operator {
operator := model.Operator(p.currentToken.Literal)
err := model.LookupOperator(operator)
if err != nil {
p.parseError(fmt.Sprintf(
"error parsing operator type %s with error: %v",
p.currentToken.Literal,
err.Error(),
))
}
return operator
}
// parseConditionType is used to parse the condition type.
func (p *Parser) parseConditionType() model.ConditionType {
conType := model.ConditionType(p.currentToken.Literal)
err := model.LookupConditionType(conType)
if err != nil {
p.parseError(fmt.Sprintf(
"error parsing condition type %s with error: %v",
p.currentToken.Literal,
err.Error(),
))
}
return conType
}
// parseConditionValue is used to parse the condition value (eg. 10 if min length of string is 10 (min10)).
func (p *Parser) parseConditionValue() string {
return p.currentToken.Literal
}
// parseError is very similar to `peekError`, except it simply takes a string message that
// gets appended to the parser's errors
func (p *Parser) parseError(msg string) {
p.errors = append(p.errors, msg)
}
// Errors is simply a helper function that returns the parser's errors
func (p *Parser) Errors() string {
return strings.Join(p.errors, ", ")
}
package validator
import (
"context"
"errors"
"fmt"
"strings"
"github.com/siherrmann/validator/helper"
"github.com/siherrmann/validator/model"
"github.com/siherrmann/validator/parser"
"github.com/siherrmann/validator/validators"
)
type ValidationFunc func(input any, astValue *model.AstValue) error
// ValidationFuncContext is a ValidationFunc that also gets the context of the validation call,
// eg. to read values injected with [Inject] by using [Get].
type ValidationFuncContext func(ctx context.Context, input any, astValue *model.AstValue) error
// Validator is the main struct for validation.
type Validator struct {
// ValidationFuncs holds the functions for `fun<name>` by name.
// Functions added with AddValidationFunc are stored wrapped as ValidationFuncContext.
ValidationFuncs map[string]ValidationFuncContext
}
// NewValidator creates a new Validator instance with an empty validation functions map.
func NewValidator() *Validator {
return &Validator{
ValidationFuncs: make(map[string]ValidationFuncContext),
}
}
// AddValidationFunc adds a custom validation function to the Validator.
// The function can be used in validation requirements with the name provided (`fun<name>`).
// It replaces a function with the same name. Use AddValidationFuncContext to read injected values.
func (r *Validator) AddValidationFunc(fn ValidationFunc, name string) {
r.AddValidationFuncContext(func(_ context.Context, input any, astValue *model.AstValue) error {
return fn(input, astValue)
}, name)
}
// AddValidationFuncContext adds a custom validation function that gets the context of the validation call.
// The function can be used in validation requirements with the name provided (`fun<name>`),
// values injected with [Inject] can be read in it with [Get].
// It replaces a function with the same name.
func (r *Validator) AddValidationFuncContext(fn ValidationFuncContext, name string) {
if r.ValidationFuncs == nil {
r.ValidationFuncs = make(map[string]ValidationFuncContext)
}
r.ValidationFuncs[name] = fn
}
// Validate validates a given struct by the given tagType.
// It checks if the keys are in the struct and validates the values.
// It returns an error if the validation fails.
//
// Extraction is cached per (type, tagType) after the first call for that combination
// — see getCachedValidationsFromStruct. Use GetValidationsFromStruct directly if a
// fresh, uncached extraction is required.
func (r *Validator) Validate(v any, tagType ...string) error {
return r.ValidateContext(context.Background(), v, tagType...)
}
// ValidateContext is Validate with the context of the validation call,
// which holds the values injected with [Inject].
func (r *Validator) ValidateContext(ctx context.Context, v any, tagType ...string) error {
tagTypeSet := model.VLD
if len(tagType) > 0 {
tagTypeSet = tagType[0]
}
jsonMap := map[string]any{}
err := helper.UnmapStructToJsonMap(v, &jsonMap)
if err != nil {
return fmt.Errorf("error unmapping struct to json map: %v", err)
}
validations, err := getCachedValidationsFromStruct(v, tagTypeSet)
if err != nil {
return fmt.Errorf("error getting validations from struct: %w", err)
}
_, err = r.ValidateWithValidationContext(ctx, jsonMap, validations)
if err != nil {
return fmt.Errorf("error validating struct: %w", err)
}
return nil
}
// ValidateAndUpdate validates a given JsonMap by the given validations and updates the struct.
// It checks if the keys are in the map, validates the values and updates the struct if the validation passes.
// It returns an error if the validation fails or if the struct cannot be updated.
//
// Extraction is cached per (type, tagType), same as Validate.
func (r *Validator) ValidateAndUpdate(jsonInput map[string]any, structToUpdate any, tagType ...string) error {
return r.ValidateAndUpdateContext(context.Background(), jsonInput, structToUpdate, tagType...)
}
// ValidateAndUpdateContext is ValidateAndUpdate with the context of the validation call,
// which holds the values injected with [Inject].
func (r *Validator) ValidateAndUpdateContext(ctx context.Context, jsonInput map[string]any, structToUpdate any, tagType ...string) error {
tagTypeSet := model.VLD
if len(tagType) > 0 {
tagTypeSet = tagType[0]
}
validations, err := getCachedValidationsFromStruct(structToUpdate, tagTypeSet)
if err != nil {
return fmt.Errorf("error getting validations from struct: %w", err)
}
validatedMap, err := r.ValidateWithValidationContext(ctx, jsonInput, validations)
if err != nil {
return fmt.Errorf("error validating struct: %w", err)
}
err = helper.MapJsonMapToStruct(validatedMap, structToUpdate)
if err != nil {
return fmt.Errorf("error mapping json map to struct: %v", err)
}
return nil
}
// ValidateAndUpdateWithValidation validates a given JsonMap by the given validations and updates the map.
// It checks if the keys are in the map, validates the values and updates the map if the validation passes.
// It returns an error if the validation fails or if the map cannot be updated.
func (r *Validator) ValidateAndUpdateWithValidation(jsonInput map[string]any, mapToUpdate *map[string]any, validations []model.Validation) error {
return r.ValidateAndUpdateWithValidationContext(context.Background(), jsonInput, mapToUpdate, validations)
}
// ValidateAndUpdateWithValidationContext is ValidateAndUpdateWithValidation with the context of the validation call,
// which holds the values injected with [Inject].
func (r *Validator) ValidateAndUpdateWithValidationContext(ctx context.Context, jsonInput map[string]any, mapToUpdate *map[string]any, validations []model.Validation) error {
validatedValues, err := r.ValidateWithValidationContext(ctx, jsonInput, validations)
if err != nil {
return fmt.Errorf("error validating json map: %w", err)
}
for k, v := range validatedValues {
(*mapToUpdate)[k] = v
}
return nil
}
// ValidateWithValidation validates a given JsonMap by the given validations.
// This is the main validation function that is used for all validation.
// It checks if the keys are in the map, validates the values and returns a new JsonMap.
//
// If a validation has groups, it checks if the values are valid for the groups.
// If a validation has a key that is already in the map, it returns an error.
//
// All fields are validated, also if one is invalid. The errors of invalid fields (that are not in a group)
// are returned together as [model.FieldErrors], with the JsonMap of the valid fields.
// Any other error (eg. a duplicate key or a failed group) is returned with an empty JsonMap.
//
// It returns a new JsonMap with the validated values or an error if the validation fails.
func (r *Validator) ValidateWithValidation(jsonInput map[string]any, validations []model.Validation) (map[string]any, error) {
return r.ValidateWithValidationContext(context.Background(), jsonInput, validations)
}
// ValidateWithValidationContext is ValidateWithValidation with the context of the validation call,
// which holds the values injected with [Inject].
func (r *Validator) ValidateWithValidationContext(ctx context.Context, jsonInput map[string]any, validations []model.Validation) (map[string]any, error) {
return r.validateWithScope(ctx, jsonInput, validations, nil)
}
// validateWithScope is ValidateWithValidation for a level below the given parent scope (nil for the top level).
//
// The scope of this level is only created if a validation of this level (or below) uses other fields,
// so validations without `rel` or `$` do not pay for it.
func (r *Validator) validateWithScope(ctx context.Context, jsonInput map[string]any, validations []model.Validation, parent *scope) (map[string]any, error) {
var sc *scope
for i := range validations {
if validations[i].UsesFields() {
sc = &scope{current: jsonInput, parent: parent}
break
}
}
groups := map[string]*model.Group{}
groupSize := map[string]int{}
groupErrors := map[string][]error{}
fieldErrors := model.FieldErrors{}
validateValues := map[string]any{}
for validationIndex := range validations {
validation := validations[validationIndex]
if len(validation.Key) > 0 && hasKeyBefore(validations, validationIndex) {
return map[string]any{}, fmt.Errorf("duplicate validation key: %v", validation.Key)
}
for _, g := range validation.Groups {
groups[g.Name] = g
groupSize[g.Name]++
}
jsonValue, ok, err := r.validateField(ctx, jsonInput, &validation, sc)
if err != nil {
if len(validation.Groups) == 0 {
fieldErrors = append(fieldErrors, err)
}
for _, group := range validation.Groups {
groupErrors[group.Name] = append(groupErrors[group.Name], err)
}
continue
} else if !ok {
continue
}
validateValues[validation.Key] = jsonValue
}
err := validators.ValidateGroups(groups, groupSize, groupErrors)
if err != nil {
return map[string]any{}, err
}
if len(fieldErrors) > 0 {
return validateValues, fieldErrors
}
return validateValues, nil
}
// hasKeyBefore reports if a validation before index i has the same key as validation i.
func hasKeyBefore(validations []model.Validation, i int) bool {
for j := 0; j < i; j++ {
if validations[j].Key == validations[i].Key {
return true
}
}
return false
}
// validateField validates the value of a single validation in the given JsonMap.
// It returns the validated value and if the value should be added to the validated JsonMap.
//
// A requirement that depends on other fields (`rel` or `$`) is also checked if the key is missing
// or the value is empty with omitempty, with the value null (or ""). This makes conditional requirements
// like `rel(type equoci) => min1` possible. The field is then not added to the validated JsonMap.
func (r *Validator) validateField(ctx context.Context, jsonInput map[string]any, validation *model.Validation, sc *scope) (any, bool, error) {
skipResult := false
jsonValue, ok := jsonInput[validation.Key]
if !ok {
if validation.Default != "" {
jsonValue = validation.Default
} else if strings.TrimSpace(validation.Requirement) == string(model.NONE) {
return nil, false, nil
} else if requirementUsesFields(validation) {
skipResult = true
} else {
return nil, false, fmt.Errorf("json %v key not in map", validation.Key)
}
}
if validation.OmitEmpty && jsonValue == "" {
if !requirementUsesFields(validation) {
return nil, false, nil
}
skipResult = true
}
if jsonValue != nil {
switch validation.Type {
case model.String, model.Int, model.Float, model.Bool:
coerced, coerceErr := helper.AnyToType(jsonValue, validation.Type.ToReflectType())
if coerceErr == nil {
jsonValue = coerced
}
}
}
var err error
switch validation.Type {
case model.Struct:
// Without inner validations (eg. a struct without tags) the value is taken as it is.
if jsonValueMap, ok := jsonValue.(map[string]any); ok && validation.Inner() != nil {
jsonValue, err = r.validateStruct(ctx, jsonValueMap, validation, sc)
if err != nil {
return nil, false, fmt.Errorf("field %v invalid: %w", validation.Key, err)
}
} else {
err = r.validateValue(ctx, jsonValue, validation, sc)
}
case model.Array:
if helper.IsArray(jsonValue) && validation.Inner() != nil {
jsonArray, ok := jsonValue.([]any)
if !ok {
return nil, false, fmt.Errorf("field %v must be of type array, was %T", validation.Key, jsonValue)
}
// The requirement of the list itself (eg. `min1` or `unqname`).
if err := r.validateValue(ctx, jsonArray, validation, sc); err != nil {
if validation.Default != "" {
return validation.Default, true, nil
}
return nil, false, fmt.Errorf("field %v invalid: %w", validation.Key, err)
}
validatedArray := []any{}
for _, jsonValueInner := range jsonArray {
jsonValueInnerMap, err := helper.GetValidMap(jsonValueInner)
if err != nil {
return nil, false, fmt.Errorf("field %v invalid: %w", validation.Key, err)
}
validatedInnerMap, err := r.validateWithScope(ctx, jsonValueInnerMap, validation.Inner(), sc)
if err != nil {
return nil, false, fmt.Errorf("field %v invalid: %w", validation.Key, err)
}
validatedArray = append(validatedArray, validatedInnerMap)
}
jsonValue = validatedArray
} else if helper.IsArray(jsonValue) {
err = r.validateValue(ctx, jsonValue, validation, sc)
} else if helper.IsString(jsonValue) {
// Check if the value is a string from a url value.
jsonValue = []string{jsonValue.(string)}
err = r.validateValue(ctx, jsonValue, validation, sc)
} else if jsonValue == nil {
err = r.validateValue(ctx, jsonValue, validation, sc)
} else if validation.Inner() == nil {
// A lone value (e.g. a single form value) is treated as a one-element list.
jsonValue = []any{jsonValue}
err = r.validateValue(ctx, jsonValue, validation, sc)
}
default:
err = r.validateValue(ctx, jsonValue, validation, sc)
}
if err != nil {
if validation.Default != "" {
return validation.Default, true, nil
}
return nil, false, fmt.Errorf("field %v invalid: %w", validation.Key, err)
}
if skipResult {
return nil, false, nil
}
return jsonValue, true, nil
}
// requirementUsesFields reports if the requirement of the validation contains `rel` or a `$` reference.
// It is only called for missing or empty values, so parsing an uncached requirement here is fine.
func requirementUsesFields(validation *model.Validation) bool {
astValue, err := getRequirementAST(validation)
return err == nil && astValue.UsesFields
}
// validateStruct validates the JsonMap of a struct field by its inner validations.
//
// Without a requirement on the struct field all inner fields have to be valid.
// With a requirement, the requirement is checked on the JsonMap itself (eg. min and max check the number of keys).
// If the JsonMap is empty and fulfills the requirement, the inner validations are skipped.
// If the requirement contains cmn or cmx, invalid inner fields are left out instead of failing
// and cmn/cmx check the number of correct inner fields (the fields in the validated JsonMap).
func (r *Validator) validateStruct(ctx context.Context, jsonValueMap map[string]any, validation *model.Validation, sc *scope) (map[string]any, error) {
astValue, err := getRequirementAST(validation)
if err != nil {
return nil, err
}
if !astValue.HasCondition(model.ConditionType.IsRequirement) {
return r.validateWithScope(ctx, jsonValueMap, validation.Inner(), sc)
}
if !astValue.HasCondition(model.ConditionType.IsCorrect) {
err = r.runConditions(ctx, jsonValueMap, astValue, nil, sc)
if err != nil {
return nil, err
} else if len(jsonValueMap) == 0 {
return map[string]any{}, nil
}
return r.validateWithScope(ctx, jsonValueMap, validation.Inner(), sc)
}
validated, innerErr := r.validateWithScope(ctx, jsonValueMap, validation.Inner(), sc)
var fieldErrors model.FieldErrors
if innerErr != nil && !errors.As(innerErr, &fieldErrors) {
return nil, innerErr
}
correct := len(validated)
err = r.runConditions(ctx, jsonValueMap, astValue, &correct, sc)
if err != nil {
if innerErr != nil {
return nil, fmt.Errorf("%w, inner errors: %w", err, innerErr)
}
return nil, err
} else if len(jsonValueMap) == 0 {
return map[string]any{}, nil
}
return validated, nil
}
// getRequirementAST returns the cached AST of the validation or parses the requirement.
func getRequirementAST(validation *model.Validation) (*model.AstValue, error) {
if validation.RequirementAST != nil {
return validation.RequirementAST, nil
}
p := parser.NewParser()
v, err := p.ParseValidation(validation.Requirement)
if err != nil {
return nil, err
}
return v.RootValue, nil
}
// ValidateValueWithParser validates a value against a given validation using the parser.
// It parses the validation requirement and runs the validation function on the input value.
//
// A requirement with `rel` or `$` references can not be validated with this function,
// because the other fields are unknown. Use ValidateWithValidation instead.
//
// It returns an error if the validation fails.
func (r *Validator) ValidateValueWithParser(input any, validation *model.Validation) error {
return r.validateValue(context.Background(), input, validation, nil)
}
// validateValue validates a value against a given validation with the scope of its level.
func (r *Validator) validateValue(ctx context.Context, input any, validation *model.Validation, sc *scope) error {
astValue, err := getRequirementAST(validation)
if err != nil {
return err
}
return r.runConditions(ctx, input, astValue, nil, sc)
}
// RunValidatorsOnConditionGroup runs the validators for each condition in the [astValue] on the [input].
// If the condition is a group, it recursively calls itself on the group.
// If the operator is AND, it returns an error if any condition fails.
// If the operator is OR, it collects all errors and returns them if all conditions fail.
// If the operator is IMPLIES (`=>`), the group is fulfilled if the premise fails, otherwise the consequence has to be fulfilled.
// [correct] is the number of correct inner fields for cmn and cmx, it is nil if the input has no inner validations.
//
// A requirement with `rel` or `$` references can not be validated with this function,
// because the other fields are unknown. Use ValidateWithValidation instead.
func (r *Validator) RunValidatorsOnConditionGroup(input any, astValue *model.AstValue, correct *int) error {
return r.runConditions(context.Background(), input, astValue, correct, nil)
}
// runConditions is RunValidatorsOnConditionGroup with the scope of the validated level.
func (r *Validator) runConditions(ctx context.Context, input any, astValue *model.AstValue, correct *int, sc *scope) error {
onlyOr := isOnlyOr(astValue.ConditionGroup)
var errors []error
for i, v := range astValue.ConditionGroup {
var err error
switch v.Type {
case model.EMPTY:
return nil
case model.GROUP:
err = r.runConditions(ctx, input, v, correct, sc)
case model.CONDITION:
var fatal bool
if v.Ref != nil {
fatal, err = r.runFieldCondition(ctx, input, v, correct, sc)
} else {
fatal, err = r.runCondition(ctx, input, v, correct)
}
if fatal {
return err
}
}
if err == nil && onlyOr {
// One fulfilled condition is enough, the other conditions do not have to be checked.
return nil
}
if err != nil {
if v.Operator == model.IMPLIES {
// The premise is not fulfilled, so the consequence does not have to be.
return nil
} else if i > 0 && astValue.ConditionGroup[i-1].Operator == model.IMPLIES {
return fmt.Errorf("%w (required because of %v)", err, premiseToString(astValue.ConditionGroup[i-1]))
} else if (i == 0 && v.Operator == model.OR) || (i > 0 && astValue.ConditionGroup[i-1].Operator == model.OR) {
errors = append(errors, err)
} else {
return err
}
}
}
if len(astValue.ConditionGroup) > 0 && len(errors) >= len(astValue.ConditionGroup) {
return fmt.Errorf("no condition fulfilled, all errors: %v", errors)
}
return nil
}
// isOnlyOr reports if all conditions of the group are connected with OR.
func isOnlyOr(conditions model.ConditionGroup) bool {
if len(conditions) < 2 {
return false
}
for _, v := range conditions[:len(conditions)-1] {
if v.Operator != model.OR {
return false
}
}
return true
}
// runCondition runs the validator of a single condition (without `rel` or `$` reference).
// fatal reports a configuration error (eg. an unknown function), that is returned also inside an OR group.
func (r *Validator) runCondition(ctx context.Context, input any, v *model.AstValue, correct *int) (fatal bool, err error) {
switch v.ConditionType {
case model.NONE, model.DEF:
return false, nil
case model.EQUAL:
err = validators.ValidateEqual(input, v)
case model.NOT_EQUAL:
err = validators.ValidateNotEqual(input, v)
case model.MIN_VALUE:
err = validators.ValidateMin(input, v)
case model.MAX_VALUE:
err = validators.ValidateMax(input, v)
case model.CONTAINS:
err = validators.ValidateContains(input, v)
case model.NOT_CONTAINS:
err = validators.ValidateNotContains(input, v)
case model.FROM:
err = validators.ValidateFrom(input, v)
case model.NOT_FROM:
err = validators.ValidateNotFrom(input, v)
case model.REGX:
err = validators.ValidateRegex(input, v)
case model.IS_TYPE:
err = validators.ValidateIsType(input, v)
case model.UNIQUE:
err = validators.ValidateUnique(input, v)
case model.CORRECT_MIN, model.CORRECT_MAX:
if correct == nil {
return true, fmt.Errorf("%w: %v is only usable on struct fields with inner validations", model.ErrInvalidRequirement, v.ConditionType)
} else if v.ConditionType == model.CORRECT_MIN {
err = validators.ValidateCorrectMin(*correct, v)
} else {
err = validators.ValidateCorrectMax(*correct, v)
}
case model.FUNC:
fun, ok := r.ValidationFuncs[v.ConditionValue]
if !ok {
return true, fmt.Errorf("%w: unknown validation function: %v", model.ErrInvalidRequirement, v.ConditionValue)
}
err = fun(ctx, input, v)
default:
return true, fmt.Errorf("%w: unknown condition type: %v", model.ErrInvalidRequirement, v.ConditionType)
}
return false, err
}
package validator
import (
"reflect"
"sync"
"github.com/siherrmann/validator/model"
)
// validationCacheKey identifies a cached extraction by both the struct type and the
// tag type it was extracted under, since the same struct type can be validated under
// different tag types (e.g. "vld" for input validation, a custom tag for updates) with
// different requirements per field.
type validationCacheKey struct {
structType reflect.Type
tagType string
}
// validationCache holds the result of GetValidationsFromStruct per (struct type, tag
// type). Extraction walks the struct by reflection and parses every tagged field's
// requirement into an AST — expensive work that only ever depends on the type, never
// on the values a particular call is validating, since Go struct tags are fixed at
// compile time. A sync.Map fits this: the key set is bounded by the number of struct
// types the program validates, reads vastly outnumber writes, and nothing needs
// eviction.
//
// Cached slices are shared with callers as-is, not copied. That is only safe because
// nothing downstream mutates a Validation, its Groups, or its RequirementAST after
// extraction — ValidateWithValidation and validators.ValidateGroups only ever read
// them. If that invariant changes, callers of getCachedValidationsFromStruct must be
// given a copy instead.
var validationCache sync.Map
// getCachedValidationsFromStruct returns the cached extraction for v's type and
// tagType, populating the cache on a miss. An extraction that returns an error is
// never cached, so a transient failure doesn't poison every later call for that type.
func getCachedValidationsFromStruct(v any, tagType string) ([]model.Validation, error) {
key := validationCacheKey{structType: reflect.TypeOf(v), tagType: tagType}
if cached, ok := validationCache.Load(key); ok {
return cached.([]model.Validation), nil
}
validations, err := GetValidationsFromStruct(v, tagType)
if err != nil {
return nil, err
}
validationCache.Store(key, validations)
return validations, nil
}
package validator
import (
"fmt"
"reflect"
"strings"
"github.com/siherrmann/validator/helper"
"github.com/siherrmann/validator/model"
"github.com/siherrmann/validator/parser"
)
// GetValidationsFromStruct extracts validation rules from a struct based on the provided tag type.
// It iterates over the fields of the StructModel of the struct (see helper.StructModelOf),
// so fields of embedded and inline structs are extracted on the level of the struct.
//
// A field whose type refers back to a struct that contains it (eg. `Children []Node` in Node)
// gets an InnerValidationRef to the validations of that struct instead of InnerValidation.
func GetValidationsFromStruct(in any, tagType string) ([]model.Validation, error) {
err := helper.CheckValidPointerToStruct(in)
if err != nil {
return nil, err
}
e := &extractor{tagType: tagType, building: map[reflect.Type]*[]model.Validation{}}
validations, err := e.structValidations(reflect.TypeOf(in).Elem())
if err != nil {
return nil, err
}
if e.hasRef {
markFieldUsage(validations)
}
return validations, nil
}
// GetValidationFromStructField extracts validation rules from a struct field based on the provided tag type.
// It checks the field's tag for the specified tag type and constructs a Validation object.
// The key is taken from the json tag, falls back to the yaml tag and then to the field name.
func GetValidationFromStructField(tagType string, fieldValue reflect.Value, fieldType reflect.StructField) (*model.Validation, error) {
key, omitEmpty, _ := helper.FieldKey(fieldType)
e := &extractor{tagType: tagType, building: map[reflect.Type]*[]model.Validation{}}
validation, err := e.fieldValidation(fieldType, fieldValue.Type(), key, omitEmpty)
if err != nil || validation == nil {
return validation, err
}
if e.hasRef {
validations := []model.Validation{*validation}
markFieldUsage(validations)
validation = &validations[0]
}
return validation, nil
}
// extractor holds the state of a single extraction.
type extractor struct {
tagType string
// building holds the struct types that are extracted at the moment, with a pointer
// to their validations, which is filled when the extraction of the struct is done.
building map[reflect.Type]*[]model.Validation
// hasRef is set if an InnerValidationRef was set, NoFieldUsage then has to be checked again.
hasRef bool
}
// structValidations extracts the validations of all fields of the struct type.
func (e *extractor) structValidations(structType reflect.Type) ([]model.Validation, error) {
ref := new([]model.Validation)
e.building[structType] = ref
defer delete(e.building, structType)
validations := []model.Validation{}
for _, field := range helper.StructModelOf(structType).Fields {
validation, err := e.fieldValidation(field.Field, field.Field.Type, field.Key, field.OmitEmpty)
if err != nil {
return nil, err
} else if validation == nil {
continue
}
validations = append(validations, *validation)
}
*ref = validations
return validations, nil
}
// fieldValidation extracts the validation of a field of the given type, it is nil if the field has no tag.
func (e *extractor) fieldValidation(fieldType reflect.StructField, valueType reflect.Type, key string, omitEmpty bool) (*model.Validation, error) {
validation := &model.Validation{
Key: key,
OmitEmpty: omitEmpty,
Type: model.ReflectTypeToValidatorType(valueType),
Requirement: "-",
}
tagIndex := 0
tagSplit := strings.Split(fieldType.Tag.Get(e.tagType), ", ")
if len(tagSplit) > tagIndex {
// Ignore if tag is empty, we do not want to validate this field at all
if len(tagSplit[tagIndex]) == 0 {
return nil, nil
}
validation.Requirement = tagSplit[tagIndex]
tagIndex++
// Extract default value & cache AST
p := parser.NewParser()
root, err := p.ParseValidation(validation.Requirement)
if err != nil {
return nil, fmt.Errorf("error parsing validation of field %v: %w", key, err)
}
err = checkNumberConditions(root.RootValue, validation.Type)
if err != nil {
return nil, fmt.Errorf("error parsing validation of field %v: %w %q: %w", key, model.ErrInvalidRequirement, validation.Requirement, err)
}
validation.Default = root.ExtractDefault()
validation.RequirementAST = root.RootValue
}
if len(tagSplit) > tagIndex {
var err error
validation.Groups, err = model.GetGroups(tagSplit[tagIndex])
if err != nil {
return nil, fmt.Errorf("error extracting group of field %v: %w %q: %w", key, model.ErrInvalidRequirement, tagSplit[tagIndex], err)
}
}
if innerType, ok := innerStructType(valueType); ok {
if ref, building := e.building[innerType]; building {
validation.InnerValidationRef = ref
e.hasRef = true
} else if hasTag(innerType, e.tagType, map[reflect.Type]bool{}) {
innerValidation, err := e.structValidations(innerType)
if err != nil {
return nil, fmt.Errorf("error getting inner validation from %v: %w", valueType, err)
}
validation.InnerValidation = innerValidation
}
}
if validation.RequirementAST.HasCondition(model.ConditionType.IsCorrect) && (validation.Type != model.Struct || (validation.InnerValidation == nil && validation.InnerValidationRef == nil)) {
// InnerValidationRef is not filled yet for a recursive type, so Inner() can not be used here.
return nil, fmt.Errorf("error parsing validation of field %v: %w %q: cmn and cmx are only usable on struct fields with inner validations", key, model.ErrInvalidRequirement, validation.Requirement)
}
validation.NoFieldUsage = !requirementOrInnerUsesFields(validation)
return validation, nil
}
// hasTag reports if a field of the struct type or of one of its inner structs has the tag.
// A struct without any tag has no inner validations, its value is taken as it is.
func hasTag(structType reflect.Type, tagType string, seen map[reflect.Type]bool) bool {
seen[structType] = true
for _, field := range helper.StructModelOf(structType).Fields {
if field.Field.Tag.Get(tagType) != "" {
return true
}
if innerType, ok := innerStructType(field.Field.Type); ok && !seen[innerType] && hasTag(innerType, tagType, seen) {
return true
}
}
return false
}
// checkNumberConditions returns an error if an `equ` or `neq` condition of an int or float field
// (or of a list or map, where the length is compared) has a value that can not be converted to a number.
// Conditions on other fields (`rel`) and references (`$`) are only known while validating.
func checkNumberConditions(astValue *model.AstValue, validatorType model.ValidatorType) error {
var numberType reflect.Type
switch validatorType {
case model.Int, model.Array, model.Map:
numberType = reflect.TypeOf(0)
case model.Float:
numberType = reflect.TypeOf(0.0)
default:
return nil
}
for _, v := range astValue.ConditionGroup {
switch {
case v.Type == model.GROUP:
if err := checkNumberConditions(v, validatorType); err != nil {
return err
}
case v.Ref != nil || (v.ConditionType != model.EQUAL && v.ConditionType != model.NOT_EQUAL):
continue
default:
if _, err := helper.AnyToType(v.ConditionValue, numberType); err != nil {
return fmt.Errorf("condition %v%v on a field of type %v, value %v is not a number", v.ConditionType, v.ConditionValue, validatorType, v.ConditionValue)
}
}
}
return nil
}
// innerStructType returns the struct type of a struct, pointer to struct or slice/array of structs.
func innerStructType(valueType reflect.Type) (reflect.Type, bool) {
switch valueType.Kind() {
case reflect.Slice, reflect.Array:
valueType = valueType.Elem()
return valueType, valueType.Kind() == reflect.Struct
case reflect.Ptr:
valueType = valueType.Elem()
}
return valueType, valueType.Kind() == reflect.Struct
}
// requirementOrInnerUsesFields reports if the requirement of the validation or one of its inner validations
// uses `rel` or a `$` reference. An InnerValidationRef counts as not using fields here, see markFieldUsage.
func requirementOrInnerUsesFields(validation *model.Validation) bool {
if validation.RequirementAST != nil && validation.RequirementAST.UsesFields {
return true
}
for i := range validation.InnerValidation {
if validation.InnerValidation[i].UsesFields() {
return true
}
}
return false
}
// markFieldUsage sets NoFieldUsage to false for all validations whose inner validations use fields
// through an InnerValidationRef. It repeats until nothing changes, because a reference can be part of a cycle.
func markFieldUsage(validations []model.Validation) {
for markFieldUsageOnce(validations, map[*model.Validation]bool{}) {
}
}
func markFieldUsageOnce(validations []model.Validation, seen map[*model.Validation]bool) (changed bool) {
if len(validations) == 0 || seen[&validations[0]] {
return false
}
seen[&validations[0]] = true
for i := range validations {
validation := &validations[i]
inner := validation.Inner()
if markFieldUsageOnce(inner, seen) {
changed = true
}
if !validation.NoFieldUsage {
continue
}
for j := range inner {
if inner[j].UsesFields() {
validation.NoFieldUsage = false
changed = true
break
}
}
}
return changed
}
package validator
import (
"context"
"maps"
)
// This file holds the values injected for a single validation call,
// used by `${name}` in requirements and by functions added with AddValidationFuncContext.
// injectedKey is the context key of the injected values.
type injectedKey struct{}
// Inject returns a copy of ctx with the value injected under the given key.
// The value can be used in requirements with `${key}` (eg. `equ${api_key}` or `rel(${role} equadmin) => min1`)
// and read with [Get] in functions added with AddValidationFuncContext.
//
// The values belong to the context, so they only exist for the validation calls with this context
// (eg. a single request). The given context is not changed, so Inject is safe for concurrent use.
//
// The unpack functions (eg. UnmarshalAndValidate) use the context of the request,
// all other functions have a Context variant (eg. ValidateContext).
func Inject(ctx context.Context, key string, value any) context.Context {
if ctx == nil {
ctx = context.Background()
}
// All values are kept in one map, so a lookup is one ctx.Value call, regardless of the number of values.
// The map is copied, because the map of the given context may be used by other contexts.
current, _ := ctx.Value(injectedKey{}).(map[string]any)
values := make(map[string]any, len(current)+1)
maps.Copy(values, current)
values[key] = value
return context.WithValue(ctx, injectedKey{}, values)
}
// Get returns the value injected under the given key with [Inject].
// ok is false if no value was injected under the key or if it is not of type T.
func Get[T any](ctx context.Context, key string) (value T, ok bool) {
injected, found := injectedValue(ctx, key)
if !found {
return value, false
}
value, ok = injected.(T)
return value, ok
}
// injectedValue returns the value injected under the given key.
func injectedValue(ctx context.Context, key string) (any, bool) {
if ctx == nil {
return nil, false
}
values, _ := ctx.Value(injectedKey{}).(map[string]any)
value, ok := values[key]
return value, ok
}
package validator
import (
"context"
"crypto/subtle"
"fmt"
"reflect"
"github.com/siherrmann/validator/helper"
"github.com/siherrmann/validator/model"
"github.com/siherrmann/validator/validators"
)
// This file holds the validation of `rel` conditions and `$` references,
// which need the values of other fields of the validated input or values injected with Inject.
// scope is one level of the validated input, used to resolve `rel` conditions and `$` references.
// A level (struct or item of a list of structs) gets its own scope pointing to the scope of the level above,
// but only if a validation on this level or below uses other fields (see validateWithScope).
type scope struct {
current map[string]any
parent *scope
}
// runFieldCondition runs a `rel` condition or a condition with a `$` reference.
//
// A `rel` condition runs its inner conditions on the value of the related field (null if missing).
// A `$` reference is resolved to the value of the referenced field. `frm` and `nfr` accept a list
// (or the keys of a map) as reference, all other conditions need a single value.
// The resolved value is used in a new condition, because the AST is shared and must not be modified.
//
// An injected value (`${name}`) is handled by runInjectedCondition.
func (r *Validator) runFieldCondition(ctx context.Context, input any, v *model.AstValue, correct *int, sc *scope) (fatal bool, err error) {
if v.Ref.Injected {
return r.runInjectedCondition(ctx, input, v, correct, sc)
}
if sc == nil {
return true, fmt.Errorf("%w: %v with field %v can only be validated together with the other fields", model.ErrInvalidRequirement, v.ConditionType, v.Ref.Raw)
}
value, found, err := resolveFieldRef(sc, v.Ref)
if err != nil {
return true, err
}
if v.ConditionType == model.RELATION {
if err := r.runConditions(ctx, value, v, nil, sc); err != nil {
if v.Operator == model.IMPLIES {
// A premise that is not fulfilled is the normal case, the error is not shown.
return false, err
}
return false, fmt.Errorf("related field %v invalid: %v", v.Ref.Raw, err)
}
return false, nil
}
if !found || value == nil {
return false, fmt.Errorf("referenced field %v is not given", v.Ref.Raw)
}
return r.runResolvedCondition(ctx, input, v, value, correct)
}
// runInjectedCondition runs a `rel` condition or a condition with an injected value (`${name}`).
//
// Injected values are often secrets (eg. an api key), so they never appear in an error message,
// errors only name the injected value (eg. `${api_key}`). `equ` and `neq` compare strings in
// constant time, so the value can not be guessed by measuring the time of the validation.
//
// A missing injected value is null for `rel` (like a missing field). For all other conditions
// it is a configuration error (the value was not injected), that is also returned inside an OR group.
func (r *Validator) runInjectedCondition(ctx context.Context, input any, v *model.AstValue, correct *int, sc *scope) (fatal bool, err error) {
name := v.Ref.Path[0]
value, found := injectedValue(ctx, name)
if b, ok := value.([]byte); ok {
value = string(b)
}
if v.ConditionType == model.RELATION {
if err := r.runConditions(ctx, value, v, nil, sc); err != nil {
if v.Operator == model.IMPLIES {
// A premise that is not fulfilled is the normal case, the error is not shown.
return false, err
}
return false, fmt.Errorf("injected value %v does not fulfill %v", v.Ref.Raw, v.AstGroupToString())
}
return false, nil
}
if !found || value == nil {
return true, fmt.Errorf("injected value %v is not given, it has to be injected with validator.Inject", v.Ref.Raw)
}
if check, ok := input.(string); ok && (v.ConditionType == model.EQUAL || v.ConditionType == model.NOT_EQUAL) {
if secret, ok := value.(string); ok {
equal := subtle.ConstantTimeCompare([]byte(check), []byte(secret)) == 1
if equal != (v.ConditionType == model.EQUAL) {
return false, injectedError(v)
}
return false, nil
}
}
fatal, err = r.runResolvedCondition(ctx, input, v, value, correct)
if err != nil && !fatal {
return false, injectedError(v)
}
return fatal, err
}
// injectedError is the error of a condition with an injected value, without the value itself.
func injectedError(v *model.AstValue) error {
return fmt.Errorf("value does not fulfill %v%v", v.ConditionType, v.Ref.Raw)
}
// runResolvedCondition runs a condition with the resolved value of a `$` reference or an injected value.
func (r *Validator) runResolvedCondition(ctx context.Context, input any, v *model.AstValue, value any, correct *int) (fatal bool, err error) {
switch v.ConditionType {
case model.FROM, model.NOT_FROM:
return false, validators.ValidateFromValues(input, value, v.ConditionType == model.NOT_FROM, v.Ref.Raw)
}
conditionValue, err := helper.AnyToString(value)
if err != nil {
return false, fmt.Errorf("referenced field %v has to be a single value for %v: %v", v.Ref.Raw, v.ConditionType, err)
}
// A new condition without the values precomputed by the parser, they belong to the `$` value.
resolved := model.AstValue{
Type: model.CONDITION,
ConditionType: v.ConditionType,
ConditionValue: conditionValue,
Start: v.Start,
End: v.End,
}
return r.runCondition(ctx, input, &resolved, correct)
}
// resolveFieldRef returns the value of the referenced field, starting at the given scope.
// found is false if a field of the path does not exist.
func resolveFieldRef(sc *scope, ref *model.FieldRef) (value any, found bool, err error) {
current := sc
if ref.Root {
for current.parent != nil {
current = current.parent
}
}
for i := 0; i < ref.Up; i++ {
if current.parent == nil {
return nil, false, fmt.Errorf("field path %v goes above the top level", ref.Raw)
}
current = current.parent
}
value = current.current
for _, segment := range ref.Path {
value, found = lookupField(value, segment)
if !found {
return nil, false, nil
}
}
return value, true, nil
}
// lookupField returns the field of a JsonMap. On a list it returns the field of every item.
func lookupField(value any, name string) (any, bool) {
switch v := value.(type) {
case map[string]any:
field, ok := v[name]
return field, ok
case []any:
fields := make([]any, 0, len(v))
for _, item := range v {
if field, ok := lookupField(item, name); ok {
fields = append(fields, field)
}
}
return fields, true
case nil:
return nil, false
}
rv := reflect.ValueOf(value)
switch rv.Kind() {
case reflect.Map:
return helper.MapValue(value, name)
case reflect.Slice, reflect.Array:
fields := make([]any, 0, rv.Len())
for i := 0; i < rv.Len(); i++ {
if field, ok := lookupField(rv.Index(i).Interface(), name); ok {
fields = append(fields, field)
}
}
return fields, true
}
return nil, false
}
// premiseToString formats the premise of an implication for error messages.
func premiseToString(premise *model.AstValue) string {
if premise.Type == model.GROUP {
return "(" + premise.AstGroupToString() + ")"
}
condition := *premise
condition.Operator = ""
return condition.AstConditionToString()
}
package validator
import (
"fmt"
"io"
"net/http"
"strings"
"github.com/siherrmann/validator/helper"
"github.com/siherrmann/validator/model"
)
// All unpack functions validate with the context of the request (request.Context()),
// so values injected with Inject into the request context can be used in requirements and functions.
//
// All unpack functions read request.Body only once and only as far as the reader allows,
// so the body can be limited with http.MaxBytesReader.
// mediaTypeSource is the source of the input of a request.
type mediaTypeSource int
const (
sourceForm mediaTypeSource = iota
sourceJson
sourceYaml
)
// mediaTypeSources maps the supported media types to their source.
// Media types with the suffix `+json` (eg. `application/problem+json`) are json too.
var mediaTypeSources = map[string]mediaTypeSource{
"application/x-www-form-urlencoded": sourceForm,
"multipart/form-data": sourceForm,
"application/json": sourceJson,
"application/yaml": sourceYaml,
"application/x-yaml": sourceYaml,
"text/yaml": sourceYaml,
}
// UnpackAndValidate unpacks the input of the request by its Content-Type, validates it and updates the given struct:
//
// - `application/x-www-form-urlencoded` and `multipart/form-data`: the form values and the query (see UnmapAndValidate),
// - `application/json` (also with parameters like charset, or a media type with the suffix `+json`): the json body (see UnmarshalAndValidate),
// - `application/yaml`, `application/x-yaml` and `text/yaml`: the yaml body,
// - no Content-Type: the body as json or, if the body is empty, the query.
//
// Any other Content-Type returns model.ErrUnsupportedMediaType,
// input that can not be read or parsed returns model.ErrMalformedInput. Both are wrapped, check them with errors.Is.
// It returns an error if the unpacking, validation or update fails.
//
// For more information look at ValidateAndUpdate.
func (r *Validator) UnpackAndValidate(request *http.Request, structToUpdate any, tagType ...string) error {
mapOut, err := unpackRequest(request)
if err != nil {
return err
}
err = r.ValidateAndUpdateContext(request.Context(), mapOut, structToUpdate, tagType...)
if err != nil {
return fmt.Errorf("error updating struct: %w", err)
}
return nil
}
// UnpackAndValidateWithValidation unpacks the input of the request by its Content-Type (see UnpackAndValidate).
// It validates the map by the given validations and updates it.
// It returns an error if the unpacking, validation or update fails.
func (r *Validator) UnpackAndValidateWithValidation(request *http.Request, mapToUpdate *map[string]any, validations []model.Validation) error {
mapOut, err := unpackRequest(request)
if err != nil {
return err
}
err = r.ValidateAndUpdateWithValidationContext(request.Context(), mapOut, mapToUpdate, validations)
if err != nil {
return fmt.Errorf("error updating map: %w", err)
}
return nil
}
// unpackRequest reads the input of the request by its Content-Type, see UnpackAndValidate.
func unpackRequest(request *http.Request) (map[string]any, error) {
if request == nil {
return nil, fmt.Errorf("request is nil")
}
mediaType, err := helper.MediaType(request)
if err != nil {
return nil, fmt.Errorf("%w: %v", model.ErrUnsupportedMediaType, err)
}
if mediaType == "" {
return unpackWithoutMediaType(request)
}
source, ok := mediaTypeSources[mediaType]
if !ok && strings.HasSuffix(mediaType, "+json") {
source, ok = sourceJson, true
}
if !ok {
return nil, fmt.Errorf("%w: %v", model.ErrUnsupportedMediaType, mediaType)
}
switch source {
case sourceJson:
return unmarshalRequest(request)
case sourceYaml:
mapOut, err := helper.UnmarshalYamlRequestToJsonMap(request)
if err != nil {
return nil, fmt.Errorf("%w: error unmarshaling request body: %w", model.ErrMalformedInput, err)
}
return mapOut, nil
default:
return unmapRequest(request)
}
}
// unpackWithoutMediaType reads the body of a request without Content-Type as json.
// If there is no body or it is empty, the query is read instead.
func unpackWithoutMediaType(request *http.Request) (map[string]any, error) {
if request.Body == nil || request.Body == http.NoBody {
return unmapRequest(request)
}
defer request.Body.Close()
bodyBytes, err := io.ReadAll(request.Body)
if err != nil {
return nil, fmt.Errorf("%w: error reading request body: %w", model.ErrMalformedInput, err)
} else if len(bodyBytes) == 0 {
return unmapRequest(request)
}
mapOut, err := helper.UnmarshalJsonToJsonMap(bodyBytes)
if err != nil {
return nil, fmt.Errorf("%w: error unmarshaling request body: %w", model.ErrMalformedInput, err)
}
return mapOut, nil
}
// unmarshalRequest reads the json body of the request.
func unmarshalRequest(request *http.Request) (map[string]any, error) {
mapOut, err := helper.UnmarshalRequestToJsonMap(request)
if err != nil {
return nil, fmt.Errorf("%w: error unmarshaling request body: %w", model.ErrMalformedInput, err)
}
return mapOut, nil
}
// unmapRequest reads the form values of the request.
func unmapRequest(request *http.Request) (map[string]any, error) {
mapOut, err := helper.UnmapRequestToJsonMap(request)
if err != nil {
return nil, fmt.Errorf("%w: error unmapping form values: %w", model.ErrMalformedInput, err)
}
return mapOut, nil
}
// UnmarshalAndValidate unmarshals the json body of the request, validates it and updates the given struct.
// It returns an error if the unmarshaling, validation or update fails.
//
// For more information look at ValidateAndUpdate.
func (r *Validator) UnmarshalAndValidate(request *http.Request, structToUpdate any, tagType ...string) error {
mapOut, err := unmarshalRequest(request)
if err != nil {
return err
}
err = r.ValidateAndUpdateContext(request.Context(), mapOut, structToUpdate, tagType...)
if err != nil {
return fmt.Errorf("error updating struct: %w", err)
}
return nil
}
// UnmapAndValidate unmaps the form values of the request (the query and, for a url encoded or multipart form, the body),
// validates them and updates the given struct. Files of a multipart form are ignored.
// It returns an error if the unmapping, validation or update fails.
//
// For more information look at ValidateAndUpdate.
func (r *Validator) UnmapAndValidate(request *http.Request, structToUpdate any, tagType ...string) error {
mapOut, err := unmapRequest(request)
if err != nil {
return err
}
err = r.ValidateAndUpdateContext(request.Context(), mapOut, structToUpdate, tagType...)
if err != nil {
return fmt.Errorf("error updating struct: %w", err)
}
return nil
}
// UnmarshalAndValidateWithValidation unmarshals the json body of the request.
// It validates the map by the given validations and updates it.
// It returns an error if the unmarshaling, validation or update fails.
func (r *Validator) UnmarshalAndValidateWithValidation(request *http.Request, mapToUpdate *map[string]any, validations []model.Validation) error {
mapOut, err := unmarshalRequest(request)
if err != nil {
return err
}
err = r.ValidateAndUpdateWithValidationContext(request.Context(), mapOut, mapToUpdate, validations)
if err != nil {
return fmt.Errorf("error updating struct: %w", err)
}
return nil
}
// UnmapAndValidateWithValidation unmaps the form values of the request (see UnmapAndValidate).
// It validates the map by the given validations and updates it.
// It returns an error if the unmapping, validation or update fails.
func (r *Validator) UnmapAndValidateWithValidation(request *http.Request, mapToUpdate *map[string]any, validations []model.Validation) error {
mapOut, err := unmapRequest(request)
if err != nil {
return err
}
err = r.ValidateAndUpdateWithValidationContext(request.Context(), mapOut, mapToUpdate, validations)
if err != nil {
return fmt.Errorf("error updating struct: %w", err)
}
return nil
}
package validator
import (
"context"
"net/http"
"github.com/siherrmann/validator/model"
)
// Validate is the wrapper function for the Validate method of the Validator struct.
// More details can be found in the Validate method.
func Validate(v any, tagType ...string) error {
r := NewValidator()
return r.Validate(v, tagType...)
}
// ValidateWithValidation is the wrapper function for the ValidateWithValidation method of the Validator struct.
// More details can be found in the ValidateWithValidation method.
func ValidateWithValidation(jsonInput map[string]any, validations []model.Validation) (map[string]any, error) {
r := NewValidator()
return r.ValidateWithValidation(jsonInput, validations)
}
// ValidateAndUpdate is the wrapper function for the ValidateAndUpdate method of the Validator struct.
// More details can be found in the ValidateAndUpdate method.
func ValidateAndUpdate(jsonInput map[string]any, structToUpdate any, tagType ...string) error {
r := NewValidator()
return r.ValidateAndUpdate(jsonInput, structToUpdate, tagType...)
}
// ValidateAndUpdateWithValidation is the wrapper function for the ValidateAndUpdateWithValidation method of the Validator struct.
// More details can be found in the ValidateAndUpdateWithValidation method.
func ValidateAndUpdateWithValidation(jsonInput map[string]any, mapToUpdate *map[string]any, validations []model.Validation) error {
r := NewValidator()
return r.ValidateAndUpdateWithValidation(jsonInput, mapToUpdate, validations)
}
// UnpackAndValidate is the wrapper function for the UnpackAndValidate method of the Validator struct.
// More details can be found in the UnpackAndValidate method.
func UnpackAndValidate(request *http.Request, structToUpdate any, tagType ...string) error {
r := NewValidator()
return r.UnpackAndValidate(request, structToUpdate, tagType...)
}
// UnpackAndValidateWithValidation is the wrapper function for the UnpackAndValidateWithValidation method of the Validator struct.
// More details can be found in the UnpackAndValidateWithValidation method.
func UnpackAndValidateWithValidation(request *http.Request, mapToUpdate *map[string]any, validations []model.Validation) error {
r := NewValidator()
return r.UnpackAndValidateWithValidation(request, mapToUpdate, validations)
}
// UnmapAndValidate is the wrapper function for the UnmapAndValidate method of the Validator struct.
// More details can be found in the UnmapAndValidate method.
func UnmapAndValidate(request *http.Request, structToUpdate any, tagType ...string) error {
r := NewValidator()
return r.UnmapAndValidate(request, structToUpdate, tagType...)
}
// UnmarshalAndValidate is the wrapper function for the UnmarshalAndValidate method of the Validator struct.
// More details can be found in the UnmarshalAndValidate method.
func UnmarshalAndValidate(request *http.Request, structToUpdate any, tagType ...string) error {
r := NewValidator()
return r.UnmarshalAndValidate(request, structToUpdate, tagType...)
}
// UnmapAndValidateWithValidation is the wrapper function for the UnmapAndValidateWithValidation method of the Validator struct.
// More details can be found in the UnmapAndValidateWithValidation method.
func UnmapAndValidateWithValidation(request *http.Request, mapToUpdate *map[string]any, validations []model.Validation) error {
r := NewValidator()
return r.UnmapAndValidateWithValidation(request, mapToUpdate, validations)
}
// UnmarshalAndValidateWithValidation is the wrapper function for the UnmarshalAndValidateWithValidation method of the Validator struct.
// More details can be found in the UnmarshalAndValidateWithValidation method.
func UnmarshalAndValidateWithValidation(request *http.Request, mapToUpdate *map[string]any, validations []model.Validation) error {
r := NewValidator()
return r.UnmarshalAndValidateWithValidation(request, mapToUpdate, validations)
}
// UnmarshalYamlAndValidate is the wrapper function for the UnmarshalYamlAndValidate method of the Validator struct.
// More details can be found in the UnmarshalYamlAndValidate method.
func UnmarshalYamlAndValidate(yamlInput []byte, structToUpdate any, tagType ...string) error {
r := NewValidator()
return r.UnmarshalYamlAndValidate(yamlInput, structToUpdate, tagType...)
}
// UnmarshalYamlAndValidateWithValidation is the wrapper function for the UnmarshalYamlAndValidateWithValidation method of the Validator struct.
// More details can be found in the UnmarshalYamlAndValidateWithValidation method.
func UnmarshalYamlAndValidateWithValidation(yamlInput []byte, mapToUpdate *map[string]any, validations []model.Validation) error {
r := NewValidator()
return r.UnmarshalYamlAndValidateWithValidation(yamlInput, mapToUpdate, validations)
}
// ValidateContext is the wrapper function for the ValidateContext method of the Validator struct.
// More details can be found in the ValidateContext method.
func ValidateContext(ctx context.Context, v any, tagType ...string) error {
r := NewValidator()
return r.ValidateContext(ctx, v, tagType...)
}
// ValidateWithValidationContext is the wrapper function for the ValidateWithValidationContext method of the Validator struct.
// More details can be found in the ValidateWithValidationContext method.
func ValidateWithValidationContext(ctx context.Context, jsonInput map[string]any, validations []model.Validation) (map[string]any, error) {
r := NewValidator()
return r.ValidateWithValidationContext(ctx, jsonInput, validations)
}
// ValidateAndUpdateContext is the wrapper function for the ValidateAndUpdateContext method of the Validator struct.
// More details can be found in the ValidateAndUpdateContext method.
func ValidateAndUpdateContext(ctx context.Context, jsonInput map[string]any, structToUpdate any, tagType ...string) error {
r := NewValidator()
return r.ValidateAndUpdateContext(ctx, jsonInput, structToUpdate, tagType...)
}
// ValidateAndUpdateWithValidationContext is the wrapper function for the ValidateAndUpdateWithValidationContext method of the Validator struct.
// More details can be found in the ValidateAndUpdateWithValidationContext method.
func ValidateAndUpdateWithValidationContext(ctx context.Context, jsonInput map[string]any, mapToUpdate *map[string]any, validations []model.Validation) error {
r := NewValidator()
return r.ValidateAndUpdateWithValidationContext(ctx, jsonInput, mapToUpdate, validations)
}
// UnmarshalYamlAndValidateContext is the wrapper function for the UnmarshalYamlAndValidateContext method of the Validator struct.
// More details can be found in the UnmarshalYamlAndValidateContext method.
func UnmarshalYamlAndValidateContext(ctx context.Context, yamlInput []byte, structToUpdate any, tagType ...string) error {
r := NewValidator()
return r.UnmarshalYamlAndValidateContext(ctx, yamlInput, structToUpdate, tagType...)
}
// UnmarshalYamlAndValidateWithValidationContext is the wrapper function for the UnmarshalYamlAndValidateWithValidationContext method of the Validator struct.
// More details can be found in the UnmarshalYamlAndValidateWithValidationContext method.
func UnmarshalYamlAndValidateWithValidationContext(ctx context.Context, yamlInput []byte, mapToUpdate *map[string]any, validations []model.Validation) error {
r := NewValidator()
return r.UnmarshalYamlAndValidateWithValidationContext(ctx, yamlInput, mapToUpdate, validations)
}
package validator
import (
"context"
"fmt"
"github.com/siherrmann/validator/helper"
"github.com/siherrmann/validator/model"
)
// UnmarshalYamlAndValidate unmarshals given yaml ([]byte) into a JsonMap.
// It validates the map by the tagType of the given struct and updates the struct.
// It returns an error if the unmarshaling, validation or update fails.
// Invalid yaml returns model.ErrMalformedInput (wrapped).
//
// The keys are taken from the json tag, fall back to the yaml tag and then to the field name.
// For more information look at ValidateAndUpdate.
func (r *Validator) UnmarshalYamlAndValidate(yamlInput []byte, structToUpdate any, tagType ...string) error {
return r.UnmarshalYamlAndValidateContext(context.Background(), yamlInput, structToUpdate, tagType...)
}
// UnmarshalYamlAndValidateContext is UnmarshalYamlAndValidate with the context of the validation call,
// which holds the values injected with [Inject].
func (r *Validator) UnmarshalYamlAndValidateContext(ctx context.Context, yamlInput []byte, structToUpdate any, tagType ...string) error {
mapOut, err := helper.UnmarshalYamlToJsonMap(yamlInput)
if err != nil {
return fmt.Errorf("%w: error unmarshaling yaml: %w", model.ErrMalformedInput, err)
}
err = r.ValidateAndUpdateContext(ctx, mapOut, structToUpdate, tagType...)
if err != nil {
return fmt.Errorf("error updating struct: %w", err)
}
return nil
}
// UnmarshalYamlAndValidateWithValidation unmarshals given yaml ([]byte) into a JsonMap.
// It validates the map by the given validations and updates the given map.
// It returns an error if the unmarshaling, validation or update fails.
func (r *Validator) UnmarshalYamlAndValidateWithValidation(yamlInput []byte, mapToUpdate *map[string]any, validations []model.Validation) error {
return r.UnmarshalYamlAndValidateWithValidationContext(context.Background(), yamlInput, mapToUpdate, validations)
}
// UnmarshalYamlAndValidateWithValidationContext is UnmarshalYamlAndValidateWithValidation
// with the context of the validation call, which holds the values injected with [Inject].
func (r *Validator) UnmarshalYamlAndValidateWithValidationContext(ctx context.Context, yamlInput []byte, mapToUpdate *map[string]any, validations []model.Validation) error {
mapOut, err := helper.UnmarshalYamlToJsonMap(yamlInput)
if err != nil {
return fmt.Errorf("%w: error unmarshaling yaml: %w", model.ErrMalformedInput, err)
}
err = r.ValidateAndUpdateWithValidationContext(ctx, mapOut, mapToUpdate, validations)
if err != nil {
return fmt.Errorf("error updating map: %w", err)
}
return nil
}
package validators
import (
"fmt"
"reflect"
"github.com/siherrmann/validator/model"
)
func ValidateContains[T any](v T, ast *model.AstValue) error {
// A null value does not contain anything
if any(v) == nil {
return fmt.Errorf("null value does not contain %v", ast.ConditionValue)
}
switch reflect.TypeOf(v).Kind() {
case reflect.String, reflect.Array, reflect.Slice, reflect.Map:
contains, err := Contains(v, ast.ConditionValue)
if err != nil {
return fmt.Errorf("error checking contains: %v", err)
}
if !contains {
return fmt.Errorf("value does not contain %v", ast.ConditionValue)
}
default:
return fmt.Errorf("value to validate has to be a string, array, slice or map, was %v", reflect.TypeOf(v).Kind())
}
return nil
}
func ValidateNotContains[T any](v T, ast *model.AstValue) error {
// A null value does not contain anything
if any(v) == nil {
return nil
}
switch reflect.TypeOf(v).Kind() {
case reflect.String, reflect.Array, reflect.Slice, reflect.Map:
contains, err := Contains(v, ast.ConditionValue)
if err != nil {
return fmt.Errorf("error checking not contains: %v", err)
}
if contains {
return fmt.Errorf("value contains condition %v", ast.ConditionValue)
}
default:
return fmt.Errorf("value to validate has to be a string, array, slice or map, was %v", reflect.TypeOf(v).Kind())
}
return nil
}
package validators
import (
"fmt"
"reflect"
"github.com/siherrmann/validator/helper"
"github.com/siherrmann/validator/model"
)
func ValidateEqual(v any, ast *model.AstValue) error {
// A null value is not equal to any condition
if v == nil {
return fmt.Errorf("null value not equal condition %v", ast.ConditionValue)
}
var check any
var compare any
var err error
switch reflect.TypeOf(v).Kind() {
case reflect.Array, reflect.Slice, reflect.Map:
check = reflect.ValueOf(v).Len()
compare, err = helper.ConditionValueToT(check, ast.ConditionValue)
if err != nil {
return err
}
default:
check = v
compare, err = helper.ConditionValueToT(v, ast.ConditionValue)
if err != nil {
return err
}
}
if !Equal(check, compare) {
return fmt.Errorf("value not equal condition %v", ast.ConditionValue)
}
return nil
}
func ValidateNotEqual(v any, ast *model.AstValue) error {
// A null value is not equal to any condition
if v == nil {
return nil
}
var check any
var compare any
var err error
switch reflect.TypeOf(v).Kind() {
case reflect.Array, reflect.Slice, reflect.Map:
check = reflect.ValueOf(v).Len()
compare, err = helper.ConditionValueToT(check, ast.ConditionValue)
if err != nil {
return err
}
default:
check = v
compare, err = helper.ConditionValueToT(v, ast.ConditionValue)
if err != nil {
return err
}
}
if Equal(check, compare) {
return fmt.Errorf("value equal condition %v", ast.ConditionValue)
}
return nil
}
package validators
import (
"fmt"
"slices"
"github.com/siherrmann/validator/model"
)
func ValidateFrom[T any](v T, ast *model.AstValue) error {
from, err := fromWithList(v, ast, false)
if err != nil {
return fmt.Errorf("error checking from: %v", err)
}
if !from {
return fmt.Errorf("from %v does not contain value", ast.ConditionValue)
}
return nil
}
func ValidateNotFrom[T any](v T, ast *model.AstValue) error {
notFrom, err := fromWithList(v, ast, true)
if err != nil {
return fmt.Errorf("error checking not from: %v", err)
}
if !notFrom {
return fmt.Errorf("from %v does contain value", ast.ConditionValue)
}
return nil
}
// ValidateFromValues is `frm`/`nfr` with the value of a referenced field (eg. `frm$/ports.port`)
// instead of a comma separated list. The referenced value can be a single value, a list or a map (its keys).
// Like for `frm`, a list input checks every item and a map input checks every key.
// Values of different types are compared by converting the referenced value to the type of the input (eg. 80 and 80.0).
func ValidateFromValues(v any, from any, not bool, name string) error {
if fromValues(v, from, not) {
return nil
}
if not {
return fmt.Errorf("value is part of %v", name)
}
return fmt.Errorf("value is not part of %v", name)
}
// fromWithList checks a string value against the list split by the parser,
// so the condition value does not have to be split and converted on every validation.
// All other values (and ASTs built without the parser) are checked with From.
func fromWithList(v any, ast *model.AstValue, not bool) (bool, error) {
if s, ok := v.(string); ok && ast.List != nil {
return !not == slices.Contains(ast.List, s), nil
}
return From(v, ast.ConditionValue, not)
}
package validators
import (
"fmt"
"strconv"
"github.com/siherrmann/validator/model"
)
func ValidateGroups(groups map[string]*model.Group, groupSize map[string]int, groupErrors map[string][]error) error {
if len(groups) != 0 {
for groupName, group := range groups {
switch group.ConditionType {
case model.MIN_VALUE:
if len(group.ConditionValue) != 0 {
minValue, err := strconv.Atoi(group.ConditionValue)
if err != nil {
return err
} else if (groupSize[groupName] - len(groupErrors[groupName])) < minValue {
return fmt.Errorf("less then %v in group %s without error, all errors: %v", minValue, groupName, groupErrors[groupName])
}
}
case model.MAX_VALUE:
if len(group.ConditionValue) != 0 {
maxValue, err := strconv.Atoi(group.ConditionValue)
if err != nil {
return err
} else if (groupSize[groupName] - len(groupErrors[groupName])) > maxValue {
return fmt.Errorf("more then %v in group %s without error, all errors: %v", maxValue, groupName, groupErrors[groupName])
}
}
default:
return fmt.Errorf("invalid group condition type %s", group.ConditionType)
}
}
}
return nil
}
package validators
import (
"encoding/base64"
"encoding/json/jsontext"
"fmt"
"net"
"net/url"
"regexp"
"strconv"
"strings"
"time"
"unicode"
"github.com/google/uuid"
"github.com/siherrmann/validator/helper"
"github.com/siherrmann/validator/model"
)
var (
alphaRegex = regexp.MustCompile(`^[a-zA-Z]+$`)
alphanumRegex = regexp.MustCompile(`^[a-zA-Z0-9]+$`)
numericRegex = regexp.MustCompile(`^[0-9]+$`)
hexRegex = regexp.MustCompile(`^[0-9a-fA-F]+$`)
jwtRegex = regexp.MustCompile(`^[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_]+$`)
)
// ValidateIsType checks if the input is of a specific format/type defined by ast.ConditionValue.
func ValidateIsType(v any, ast *model.AstValue) error {
s, err := helper.AnyToString(v)
if err != nil {
return fmt.Errorf("value cannot be converted to string for type checking: %v", err)
}
switch ast.ConditionValue {
case "uuid":
if _, err := uuid.Parse(s); err != nil {
return fmt.Errorf("value is not a valid uuid")
}
case "unixmilli":
if num, err := strconv.ParseFloat(s, 64); err != nil || float64(int64(num)) != num {
return fmt.Errorf("value is not a valid unix timestamp in milliseconds")
}
case "timerfc3339":
_, err := time.Parse(time.RFC3339, s)
if err != nil {
return fmt.Errorf("value is not a valid rfc3339 time")
}
case "email":
if len(s) < 3 || !strings.Contains(s, "@") {
return fmt.Errorf("value is not a valid email")
}
case "url":
u, err := url.ParseRequestURI(s)
if err != nil || u.Scheme == "" || u.Host == "" {
return fmt.Errorf("value is not a valid url")
}
case "alpha":
if !alphaRegex.MatchString(s) {
return fmt.Errorf("value is not an alpha string")
}
case "alphanum":
if !alphanumRegex.MatchString(s) {
return fmt.Errorf("value is not an alphanumeric string")
}
case "numeric":
if !numericRegex.MatchString(s) {
return fmt.Errorf("value is not a numeric string")
}
case "hex":
if !hexRegex.MatchString(s) {
return fmt.Errorf("value is not a hexadecimal string")
}
case "base64":
_, err := base64.StdEncoding.DecodeString(s)
if err != nil {
return fmt.Errorf("value is not a valid base64 string")
}
case "json":
if !jsontext.Value(s).IsValid() {
return fmt.Errorf("value is not a valid json")
}
case "jwt":
if !jwtRegex.MatchString(s) {
return fmt.Errorf("value is not a valid jwt")
}
case "ip":
if net.ParseIP(s) == nil {
return fmt.Errorf("value is not a valid ip address")
}
case "ipv4":
// Decided by notation, so ipv4-mapped ipv6 addresses (e.g. ::ffff:192.168.0.1) are not accepted as ipv4
if net.ParseIP(s) == nil || strings.Contains(s, ":") {
return fmt.Errorf("value is not a valid ipv4 address")
}
case "ipv6":
if net.ParseIP(s) == nil || !strings.Contains(s, ":") {
return fmt.Errorf("value is not a valid ipv6 address")
}
case "mac":
_, err := net.ParseMAC(s)
if err != nil {
return fmt.Errorf("value is not a valid mac address")
}
case "password":
if len(s) < 8 {
return fmt.Errorf("password must be at least 8 characters long")
}
var hasUpper, hasLower, hasNumber, hasSpecial bool
for _, char := range s {
switch {
case unicode.IsUpper(char):
hasUpper = true
case unicode.IsLower(char):
hasLower = true
case unicode.IsNumber(char):
hasNumber = true
case unicode.IsPunct(char) || unicode.IsSymbol(char):
hasSpecial = true
}
}
if !hasUpper || !hasLower || !hasNumber || !hasSpecial {
return fmt.Errorf("password must contain at least one uppercase letter, one lowercase letter, one number, and one special character")
}
default:
return fmt.Errorf("unknown type check: %v", ast.ConditionValue)
}
return nil
}
package validators
import (
"fmt"
"strconv"
"github.com/siherrmann/validator/helper"
"github.com/siherrmann/validator/model"
)
func ValidateMin(v any, ast *model.AstValue) error {
check, err := helper.AnyToFloat(v)
if err != nil {
return fmt.Errorf("invalid value for min validation: %v", err)
}
compare, err := minMaxCompare(check, ast)
if err != nil {
return err
}
if !Min(check, compare) {
return fmt.Errorf("value less than minimum condition %v", ast.ConditionValue)
}
return nil
}
func ValidateMax(v any, ast *model.AstValue) error {
check, err := helper.AnyToFloat(v)
if err != nil {
return fmt.Errorf("invalid value for max validation: %v", err)
}
compare, err := minMaxCompare(check, ast)
if err != nil {
return err
}
if !Max(check, compare) {
return fmt.Errorf("value greater than maximum condition %v", ast.ConditionValue)
}
return nil
}
// minMaxCompare returns the condition value of min and max as float64.
// It uses the value parsed by the parser and only parses it, if the AST was built without the parser.
func minMaxCompare(check float64, ast *model.AstValue) (float64, error) {
if ast.HasNumber {
return ast.Number, nil
}
return helper.ConditionValueToT(check, ast.ConditionValue)
}
// ValidateCorrectMin checks if at least the condition value of inner fields are correct.
func ValidateCorrectMin(correct int, ast *model.AstValue) error {
compare, err := strconv.Atoi(ast.ConditionValue)
if err != nil {
return fmt.Errorf("invalid condition value for cmn validation: %v", err)
}
if correct < compare {
return fmt.Errorf("less than %v correct inner fields, got %v", ast.ConditionValue, correct)
}
return nil
}
// ValidateCorrectMax checks if at most the condition value of inner fields are correct.
func ValidateCorrectMax(correct int, ast *model.AstValue) error {
compare, err := strconv.Atoi(ast.ConditionValue)
if err != nil {
return fmt.Errorf("invalid condition value for cmx validation: %v", err)
}
if correct > compare {
return fmt.Errorf("more than %v correct inner fields, got %v", ast.ConditionValue, correct)
}
return nil
}
package validators
import (
"fmt"
"reflect"
"github.com/siherrmann/validator/helper"
"github.com/siherrmann/validator/model"
)
func ValidateRegex(v any, ast *model.AstValue) error {
// A null value has nothing to match
if v == nil {
return fmt.Errorf("null value does not match regex %v", ast.ConditionValue)
}
switch reflect.TypeOf(v).Kind() {
case reflect.Array, reflect.Slice, reflect.Map:
checks, err := helper.AnyToArrayOfString(v)
if err != nil {
return err
}
for _, check := range checks {
match := matchRegex(ast, check)
if !match {
return fmt.Errorf("value %v does not match regex %v", check, ast.ConditionValue)
}
}
default:
check, err := helper.AnyToString(v)
if err != nil {
return fmt.Errorf("error converting value to string: %v", err)
}
match := matchRegex(ast, check)
if !match {
return fmt.Errorf("value %v does not match regex %v", check, ast.ConditionValue)
}
}
return nil
}
// matchRegex uses the regex compiled by the parser and only compiles it, if the AST was built without the parser.
func matchRegex(ast *model.AstValue, s string) bool {
if ast.Regex != nil {
return ast.Regex.MatchString(s)
}
return Regex(s, ast.ConditionValue)
}
package validators
import (
"fmt"
"reflect"
"github.com/siherrmann/validator/helper"
"github.com/siherrmann/validator/model"
)
// uniqueMapThreshold is the number of items from which duplicates are found with a map
// instead of comparing every pair. Small lists are faster without the map allocation.
const uniqueMapThreshold = 16
// ValidateUnique checks that every item of a list is unique.
// With a condition value (eg. `unqname`), the field with this name of every item (a JsonMap) has to be unique.
// Items without this field are ignored. A null value and a map (keys are always unique) are valid.
func ValidateUnique(v any, ast *model.AstValue) error {
if v == nil {
return nil
}
rv := reflect.ValueOf(v)
switch rv.Kind() {
case reflect.Map:
return nil
case reflect.Slice, reflect.Array:
default:
return fmt.Errorf("value to validate has to be an array, slice or map, was %v", rv.Kind())
}
key := ast.ConditionValue
items := make([]any, 0, rv.Len())
comparable := true
for i := 0; i < rv.Len(); i++ {
item := rv.Index(i).Interface()
if key != "" {
field, ok, err := uniqueField(item, key)
if err != nil {
return err
} else if !ok {
continue
}
item = field
}
if item != nil && !reflect.TypeOf(item).Comparable() {
comparable = false
}
items = append(items, item)
}
if comparable && len(items) > uniqueMapThreshold {
seen := make(map[any]struct{}, len(items))
for _, item := range items {
if _, ok := seen[item]; ok {
return uniqueError(item, key)
}
seen[item] = struct{}{}
}
return nil
}
for i := 1; i < len(items); i++ {
for j := 0; j < i; j++ {
if equalValue(items[i], items[j]) {
return uniqueError(items[i], key)
}
}
}
return nil
}
// uniqueField returns the field with the given name of a list item.
func uniqueField(item any, key string) (any, bool, error) {
if rv := reflect.ValueOf(item); rv.Kind() != reflect.Map || rv.Type().Key().Kind() != reflect.String {
return nil, false, fmt.Errorf("unq%v needs a list of objects, item was %T", key, item)
}
field, ok := helper.MapValue(item, key)
return field, ok, nil
}
func uniqueError(item any, key string) error {
if key != "" {
return fmt.Errorf("value %v of %v is not unique", item, key)
}
return fmt.Errorf("value %v is not unique", item)
}
package validators
import (
"fmt"
"reflect"
"regexp"
"slices"
"strings"
"github.com/siherrmann/validator/helper"
)
func Equal[T comparable](a, equal T) bool {
return a == equal
}
func NotEqual[T comparable](a, notEqual T) bool {
return a != notEqual
}
func Min[T int | float64](v, min T) bool {
return v >= min
}
func Max[T int | float64](v, max T) bool {
return v <= max
}
func Contains(va any, contain string) (bool, error) {
if va == nil {
return false, nil
}
if s, ok := va.(string); ok {
return strings.Contains(s, contain), nil
}
rv := reflect.ValueOf(va)
rt := rv.Type()
switch rt.Kind() {
case reflect.Array, reflect.Slice:
if rv.Len() == 0 {
return false, nil
}
if rt.Elem().Kind() == reflect.Interface {
// E.g. []any from url values: compare against each item in its own type.
for i := 0; i < rv.Len(); i++ {
item := rv.Index(i).Interface()
if item == nil {
continue
}
con, err := helper.AnyToType(contain, reflect.TypeOf(item))
if err == nil && reflect.DeepEqual(item, con) {
return true, nil
}
}
return false, nil
}
con, err := helper.AnyToType(contain, rt.Elem())
if err != nil {
return false, fmt.Errorf("error converting condition to %T: %v", rt.Elem().Kind, err)
}
vaany, err := helper.ArrayToArrayOfAny(va)
if err != nil {
return false, fmt.Errorf("error converting value to array of any: %v", err)
}
return slices.Contains(vaany, con), nil
case reflect.Map:
if rv.Len() == 0 {
return false, nil
}
con, err := helper.AnyToType(contain, rt.Key())
if err != nil {
return false, fmt.Errorf("error converting condition to %T: %v", rt.Elem().Kind, err)
}
vaany, err := helper.MapKeysToArrayOfAny(va)
if err != nil {
return false, fmt.Errorf("error converting value to array of any: %v", err)
}
return slices.Contains(vaany, con), nil
default:
return false, fmt.Errorf("type %v not supported for contains", reflect.TypeOf(va))
}
}
func From(v any, from string, not bool) (bool, error) {
switch v := v.(type) {
case nil:
// A null value is not part of any list
return not, nil
case string, bool,
int, int8, int16, int32, int64,
uint, uint8, uint16, uint32, uint64,
float32, float64:
b, err := helper.ConditionValueToArrayOfAny(from, reflect.TypeOf(v))
if err != nil {
return false, err
}
return !not == slices.Contains(b, any(v)), nil
default:
switch reflect.TypeOf(v).Kind() {
case reflect.Array, reflect.Slice:
f, err := helper.ConditionValueToArrayOfAny(from, reflect.TypeOf(v).Elem())
if err != nil {
return false, err
}
conditionValues, err := helper.ArrayToArrayOfAny(f)
if err != nil {
return false, err
}
values := []any{}
rv := reflect.ValueOf(v)
for i := 0; i < rv.Len(); i++ {
avi := rv.Index(i).Interface()
values = append(values, avi)
}
return FromArray(values, conditionValues, not)
case reflect.Map:
f, err := helper.ConditionValueToArrayOfAny(from, reflect.TypeOf(v).Key())
if err != nil {
return false, err
}
conditionValues, err := helper.ArrayToArrayOfAny(f)
if err != nil {
return false, err
}
values := []any{}
rv := reflect.ValueOf(v)
for _, mk := range rv.MapKeys() {
values = append(values, mk.Interface())
}
return FromArray(values, conditionValues, not)
}
return false, fmt.Errorf("type %v not supported for From validation", reflect.TypeOf(v))
}
}
func FromArray[T comparable](v []T, from []T, not bool) (bool, error) {
for _, item := range v {
if not == slices.Contains(from, item) {
return false, nil
}
}
return true, nil
}
func Regex(s, regex string) bool {
matched, _ := regexp.MatchString(regex, s)
return matched
}
// fromValues is From with the values of a referenced field, see ValidateFromValues.
func fromValues(v any, from any, not bool) bool {
if v == nil {
// A null value is not part of any list
return not
}
rv := reflect.ValueOf(v)
switch rv.Kind() {
case reflect.Slice, reflect.Array:
for i := 0; i < rv.Len(); i++ {
if containsValue(from, rv.Index(i).Interface()) == not {
return false
}
}
return true
case reflect.Map:
iter := rv.MapRange()
for iter.Next() {
if containsValue(from, iter.Key().Interface()) == not {
return false
}
}
return true
default:
return containsValue(from, v) != not
}
}
// containsValue reports if the item is the value, an item of the list or a key of the map from.
func containsValue(from any, item any) bool {
if values, ok := from.([]any); ok {
for _, value := range values {
if equalValue(item, value) {
return true
}
}
return false
}
rv := reflect.ValueOf(from)
switch rv.Kind() {
case reflect.Invalid:
return false
case reflect.Slice, reflect.Array:
for i := 0; i < rv.Len(); i++ {
if equalValue(item, rv.Index(i).Interface()) {
return true
}
}
return false
case reflect.Map:
iter := rv.MapRange()
for iter.Next() {
if equalValue(item, iter.Key().Interface()) {
return true
}
}
return false
default:
return equalValue(item, from)
}
}
// equalValue compares two values, converting b to the type of a if the types differ.
func equalValue(a any, b any) bool {
if a == nil || b == nil {
return a == nil && b == nil
}
typeA := reflect.TypeOf(a)
if typeA == reflect.TypeOf(b) {
if typeA.Comparable() {
return a == b
}
return reflect.DeepEqual(a, b)
}
converted, err := helper.AnyToType(b, typeA)
return err == nil && reflect.DeepEqual(a, converted)
}