github.com/gocaveman/caveman@v0.0.0-20191211162744-0ddf99dbdf6e/valid/valid.go (about)

     1  // Validation rules and functionality for common cases.
     2  //
     3  // TODO: Note on i18n, English strings are provided as the simple, common case, but are not intended to be
     4  // used for translation.  Validation messages also contain Code and Data which together can be used
     5  // with the i18n package to produce properly translated messages in each language.
     6  package valid
     7  
     8  import (
     9  	"fmt"
    10  	"reflect"
    11  
    12  	"github.com/gocaveman/caveman/webutil"
    13  )
    14  
    15  var ErrNotFound = webutil.ErrNotFound
    16  
    17  // TODO: figure out how a CheckValid() (or similar) method fits into this.
    18  // While the rules are very useful, the ability to just add custom validation
    19  // code to a struct with a simple function should not be underestimated
    20  // and it should be fully supported.
    21  func Obj(obj interface{}, rules Rules) error {
    22  
    23  	objv := reflect.ValueOf(obj)
    24  	for objv.Kind() == reflect.Ptr {
    25  		objv = objv.Elem()
    26  	}
    27  
    28  	if objv.Kind() == reflect.Map {
    29  
    30  		if rules == nil {
    31  			return fmt.Errorf("valid.Obj() requires rules when validating a map")
    32  		}
    33  
    34  	} else if objv.Kind() == reflect.Struct {
    35  
    36  		if rules == nil {
    37  			var err error
    38  			rules, err = StructRules(objv.Type(), nil)
    39  			if err != nil {
    40  				return err
    41  			}
    42  		}
    43  
    44  	} else {
    45  
    46  		return fmt.Errorf("valid.Obj() does not understand objects of type %v", objv.Kind())
    47  
    48  	}
    49  
    50  	return rules.Apply(obj)
    51  }