Skip to content

Nested JSON tag paths are not respected #297

@akfaiz

Description

@akfaiz

System (please complete the following information):

  • OS: macOS
  • GO Version: 1.24
  • Pkg Version: 1.5.5

Describe the bug

When validating nested slices/structs with json tags, the generated error keys do not preserve the full JSON path.

To Reproduce

package validator_test

import (
	"testing"

	"github.com/gookit/validate"
	"github.com/stretchr/testify/assert"
)

type WithArray struct {
	Extras []ExtraInfo `validate:"required|minLen:2"`
}

type WithArrayJSON struct {
	Extras []ExtraInfoJSON `json:"extras" validate:"required|minLen:2"`
}

type ExtraInfo struct {
	Github  string `validate:"required"`
	Status1 int    `validate:"required|int"`
}

type ExtraInfoJSON struct {
	Github  string `json:"github" validate:"required"`
	Status1 int    `json:"status1" validate:"required|int"`
}

func TestValidate(t *testing.T) {
	v := validate.New(WithArray{
		Extras: []ExtraInfo{
			{
				Github:  "",
				Status1: 0,
			},
			{
				Github:  "",
				Status1: 0,
			},
		},
	})
	assert.False(t, v.Validate())
	var firstKey string
	for key := range v.Errors {
		firstKey = key
		break
	}
	assert.Equal(t, "Extras.0.Github", firstKey)

	v = validate.New(WithArrayJSON{
		Extras: []ExtraInfoJSON{
			{
				Github:  "",
				Status1: 0,
			},
			{
				Github:  "",
				Status1: 0,
			},
		},
	})
	assert.False(t, v.Validate())
	var firstKeyJSON string
	for key := range v.Errors {
		firstKeyJSON = key
		break
	}
	assert.Equal(t, "extras.0.github", firstKeyJSON)
}

Expected behavior

Expected error field key is "extras.0.github" because when not json tag is expected.

Screenshots

Error:      	Not equal:
            	expected: "extras.0.github"
            	actual  : "github"

            	Diff:
            	--- Expected
            	+++ Actual
            	@@ -1 +1 @@
            	-extras.0.github
            	+github

Additional context

Metadata

Metadata

Assignees

Labels

bugSomething isn't working

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions