Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can't validate both keys and the struct value of maps of structs #1260

Open
2 tasks done
bfabio opened this issue May 6, 2024 · 0 comments
Open
2 tasks done

Can't validate both keys and the struct value of maps of structs #1260

bfabio opened this issue May 6, 2024 · 0 comments

Comments

@bfabio
Copy link

bfabio commented May 6, 2024

  • I have looked at the documentation here first?
  • I have looked at the examples provided that may showcase my question here?

Package version eg. v9, v10:

v10

Issue, Question or Enhancement:

When you have a map with struct values, it looks there is no way to validate both the keys and the struct, you can only validate the keys OR the struct.

Code sample, to showcase or reproduce:

This works as expected, returning a validation error because Name is required in Author.

package main

import (
	"fmt"

	"github.com/go-playground/validator/v10"
)

type Book struct {
	RelatedAuthors map[string]Author `validate:"dive"`
}

type Author struct {
	Name string `validate:"required"`
}

func main() {
	validate := validator.New(validator.WithRequiredStructEnabled())

	book := Book{
		RelatedAuthors: map[string]Author{
			"12345": {},
		},
	}

	err := validate.Struct(book)
	if err != nil {
		fmt.Println("Validation error:", err)
	} else {
		fmt.Println("Validation successful")
	}
}
Validation error: Key: 'Book.RelatedAuthors[12345].Name' Error:Field validation for 'Name' failed on the 'required' tag

This validates successfully, even if Name is required

package main

import (
	"fmt"

	"github.com/go-playground/validator/v10"
)

type Book struct {
	RelatedAuthors map[string]Author `validate:"dive,keys,len=5,endkeys"`
}

type Author struct {
	Name string `validate:"required"`
}

func main() {
	validate := validator.New(validator.WithRequiredStructEnabled())

	book := Book{
		RelatedAuthors: map[string]Author{
			"12345": {},
		},
	}

	err := validate.Struct(book)
	if err != nil {
		fmt.Println("Validation error:", err)
	} else {
		fmt.Println("Validation successful")
	}
}
Validation successful

The only difference between the two testcases is:

        RelatedAuthors map[string]Author `validate:"dive"`
        // vs
	RelatedAuthors map[string]Author `validate:"dive,keys,len=5,endkeys"`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant