field_level.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package validator
  2. import "reflect"
  3. // FieldLevel contains all the information and helper functions
  4. // to validate a field
  5. type FieldLevel interface {
  6. // returns the top level struct, if any
  7. Top() reflect.Value
  8. // returns the current fields parent struct, if any or
  9. // the comparison value if called 'VarWithValue'
  10. Parent() reflect.Value
  11. // returns current field for validation
  12. Field() reflect.Value
  13. // returns the field's name with the tag
  14. // name takeing precedence over the fields actual name.
  15. FieldName() string
  16. // returns the struct field's name
  17. StructFieldName() string
  18. // returns param for validation against current field
  19. Param() string
  20. // ExtractType gets the actual underlying type of field value.
  21. // It will dive into pointers, customTypes and return you the
  22. // underlying value and it's kind.
  23. ExtractType(field reflect.Value) (value reflect.Value, kind reflect.Kind, nullable bool)
  24. // traverses the parent struct to retrieve a specific field denoted by the provided namespace
  25. // in the param and returns the field, field kind and whether is was successful in retrieving
  26. // the field at all.
  27. //
  28. // NOTE: when not successful ok will be false, this can happen when a nested struct is nil and so the field
  29. // could not be retrieved because it didn't exist.
  30. GetStructFieldOK() (reflect.Value, reflect.Kind, bool)
  31. }
  32. var _ FieldLevel = new(validate)
  33. // Field returns current field for validation
  34. func (v *validate) Field() reflect.Value {
  35. return v.flField
  36. }
  37. // FieldName returns the field's name with the tag
  38. // name takeing precedence over the fields actual name.
  39. func (v *validate) FieldName() string {
  40. return v.cf.altName
  41. }
  42. // StructFieldName returns the struct field's name
  43. func (v *validate) StructFieldName() string {
  44. return v.cf.name
  45. }
  46. // Param returns param for validation against current field
  47. func (v *validate) Param() string {
  48. return v.ct.param
  49. }
  50. // GetStructFieldOK returns Param returns param for validation against current field
  51. func (v *validate) GetStructFieldOK() (reflect.Value, reflect.Kind, bool) {
  52. return v.getStructFieldOKInternal(v.slflParent, v.ct.param)
  53. }