notblank_test.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package validators
  2. import (
  3. "testing"
  4. "gopkg.in/go-playground/validator.v9"
  5. "gopkg.in/go-playground/assert.v1"
  6. )
  7. type test struct {
  8. String string `validate:"notblank"`
  9. Array []int `validate:"notblank"`
  10. Pointer *int `validate:"notblank"`
  11. Number int `validate:"notblank"`
  12. Interface interface{} `validate:"notblank"`
  13. Func func() `validate:"notblank"`
  14. }
  15. func TestNotBlank(t *testing.T) {
  16. v := validator.New()
  17. err := v.RegisterValidation("notblank", NotBlank)
  18. assert.Equal(t, nil, err)
  19. // Errors
  20. var x *int
  21. invalid := test{
  22. String: " ",
  23. Array: []int{},
  24. Pointer: x,
  25. Number: 0,
  26. Interface: nil,
  27. Func: nil,
  28. }
  29. fieldsWithError := []string{
  30. "String",
  31. "Array",
  32. "Pointer",
  33. "Number",
  34. "Interface",
  35. "Func",
  36. }
  37. errors := v.Struct(invalid).(validator.ValidationErrors)
  38. var fields []string
  39. for _, err := range errors {
  40. fields = append(fields, err.Field())
  41. }
  42. assert.Equal(t, fieldsWithError, fields)
  43. // No errors
  44. y := 1
  45. x = &y
  46. valid := test{
  47. String: "str",
  48. Array: []int{1},
  49. Pointer: x,
  50. Number: 1,
  51. Interface: "value",
  52. Func: func() {},
  53. }
  54. err = v.Struct(valid)
  55. assert.Equal(t, nil, err)
  56. }