mirror of
https://github.com/romdo/go-validate.git
synced 2026-02-19 08:06:40 +00:00
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:
36
helpers.go
Normal file
36
helpers.go
Normal 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
|
||||
}
|
||||
Reference in New Issue
Block a user