mirror of
https://github.com/romdo/go-validate.git
synced 2026-02-19 08:06:40 +00:00
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.
37 lines
567 B
Go
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
|
|
}
|