Files
go-validate/helpers.go
Jim Myhrberg 464467ec86 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.
2021-08-22 21:53:02 +01:00

37 lines
567 B
Go

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
}