feat(validate): initial implementation

This is a bare-bones implementation of a basic validation package based
around a very simply Validatable interface:

    type Validatable interface {
        Validate() error
    }

The goal is to keep things as simple as possible, while also giving as
much control as possible over how validation logic is performed.
This commit is contained in:
2021-08-20 03:32:41 +01:00
parent 9e4b022762
commit 464467ec86
10 changed files with 2309 additions and 0 deletions

36
helpers.go Normal file
View File

@@ -0,0 +1,36 @@
package validate
import (
"reflect"
)
// RequireField returns a Error type for the given field if provided value is
// empty/zero.
func RequireField(field string, value interface{}) error {
err := &Error{Field: field, Msg: "is required"}
v := reflect.ValueOf(value)
if v.Kind() == reflect.Ptr {
if v.IsNil() {
return err
}
v = v.Elem()
}
if !v.IsValid() {
return err
}
switch v.Kind() { //nolint:exhaustive
case reflect.Map, reflect.Slice:
if v.Len() == 0 {
return err
}
default:
if v.IsZero() {
return err
}
}
return nil
}