struct.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. // Copyright 2016 Qiang Xue. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package validation
  5. import (
  6. "errors"
  7. "fmt"
  8. "reflect"
  9. "strings"
  10. )
  11. var (
  12. // ErrStructPointer is the error that a struct being validated is not specified as a pointer.
  13. ErrStructPointer = errors.New("only a pointer to a struct can be validated")
  14. )
  15. type (
  16. // ErrFieldPointer is the error that a field is not specified as a pointer.
  17. ErrFieldPointer int
  18. // ErrFieldNotFound is the error that a field cannot be found in the struct.
  19. ErrFieldNotFound int
  20. // FieldRules represents a rule set associated with a struct field.
  21. FieldRules struct {
  22. fieldPtr interface{}
  23. rules []Rule
  24. }
  25. )
  26. // Error returns the error string of ErrFieldPointer.
  27. func (e ErrFieldPointer) Error() string {
  28. return fmt.Sprintf("field #%v must be specified as a pointer", int(e))
  29. }
  30. // Error returns the error string of ErrFieldNotFound.
  31. func (e ErrFieldNotFound) Error() string {
  32. return fmt.Sprintf("field #%v cannot be found in the struct", int(e))
  33. }
  34. // ValidateStruct validates a struct by checking the specified struct fields against the corresponding validation rules.
  35. // Note that the struct being validated must be specified as a pointer to it. If the pointer is nil, it is considered valid.
  36. // Use Field() to specify struct fields that need to be validated. Each Field() call specifies a single field which
  37. // should be specified as a pointer to the field. A field can be associated with multiple rules.
  38. // For example,
  39. //
  40. // value := struct {
  41. // Name string
  42. // Value string
  43. // }{"name", "demo"}
  44. // err := validation.ValidateStruct(&value,
  45. // validation.Field(&a.Name, validation.Required),
  46. // validation.Field(&a.Value, validation.Required, validation.Length(5, 10)),
  47. // )
  48. // fmt.Println(err)
  49. // // Value: the length must be between 5 and 10.
  50. //
  51. // An error will be returned if validation fails.
  52. func ValidateStruct(structPtr interface{}, fields ...*FieldRules) error {
  53. value := reflect.ValueOf(structPtr)
  54. if value.Kind() != reflect.Ptr || !value.IsNil() && value.Elem().Kind() != reflect.Struct {
  55. // must be a pointer to a struct
  56. return NewInternalError(ErrStructPointer)
  57. }
  58. if value.IsNil() {
  59. // treat a nil struct pointer as valid
  60. return nil
  61. }
  62. value = value.Elem()
  63. errs := Errors{}
  64. for i, fr := range fields {
  65. fv := reflect.ValueOf(fr.fieldPtr)
  66. if fv.Kind() != reflect.Ptr {
  67. return NewInternalError(ErrFieldPointer(i))
  68. }
  69. ft := findStructField(value, fv)
  70. if ft == nil {
  71. return NewInternalError(ErrFieldNotFound(i))
  72. }
  73. if err := Validate(fv.Elem().Interface(), fr.rules...); err != nil {
  74. if ie, ok := err.(InternalError); ok && ie.InternalError() != nil {
  75. return err
  76. }
  77. if ft.Anonymous {
  78. // merge errors from anonymous struct field
  79. if es, ok := err.(Errors); ok {
  80. for name, value := range es {
  81. errs[name] = value
  82. }
  83. continue
  84. }
  85. }
  86. errs[getErrorFieldName(ft)] = err
  87. }
  88. }
  89. if len(errs) > 0 {
  90. return errs
  91. }
  92. return nil
  93. }
  94. // Field specifies a struct field and the corresponding validation rules.
  95. // The struct field must be specified as a pointer to it.
  96. func Field(fieldPtr interface{}, rules ...Rule) *FieldRules {
  97. return &FieldRules{
  98. fieldPtr: fieldPtr,
  99. rules: rules,
  100. }
  101. }
  102. // findStructField looks for a field in the given struct.
  103. // The field being looked for should be a pointer to the actual struct field.
  104. // If found, the field info will be returned. Otherwise, nil will be returned.
  105. func findStructField(structValue reflect.Value, fieldValue reflect.Value) *reflect.StructField {
  106. ptr := fieldValue.Pointer()
  107. for i := structValue.NumField() - 1; i >= 0; i-- {
  108. sf := structValue.Type().Field(i)
  109. if ptr == structValue.Field(i).UnsafeAddr() {
  110. // do additional type comparison because it's possible that the address of
  111. // an embedded struct is the same as the first field of the embedded struct
  112. if sf.Type == fieldValue.Elem().Type() {
  113. return &sf
  114. }
  115. }
  116. if sf.Anonymous {
  117. // delve into anonymous struct to look for the field
  118. fi := structValue.Field(i)
  119. if sf.Type.Kind() == reflect.Ptr {
  120. fi = fi.Elem()
  121. }
  122. if fi.Kind() == reflect.Struct {
  123. if f := findStructField(fi, fieldValue); f != nil {
  124. return f
  125. }
  126. }
  127. }
  128. }
  129. return nil
  130. }
  131. // getErrorFieldName returns the name that should be used to represent the validation error of a struct field.
  132. func getErrorFieldName(f *reflect.StructField) string {
  133. if tag := f.Tag.Get(ErrorTag); tag != "" {
  134. if cps := strings.SplitN(tag, ",", 2); cps[0] != "" {
  135. return cps[0]
  136. }
  137. }
  138. return f.Name
  139. }