• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: Golang: Validate Struct Fields in Slice Items

Resolved: Golang: Validate Struct Fields in Slice Items

0
By Isaac Tonny on 18/06/2022 Issue
Share
Facebook Twitter LinkedIn

Question:

I’m new to Golang.
golang version: 1.17.8
validator: “github.com/go-playground/validator/v10“
I want to validate an incoming JSON payload after loaded into nested struct data structure. Here’s my incoming JSON payload,
Here’s my user.go file,
Here’s my test function,
This test passes. However, I expected it to fail as Child.Title is marked as required. I expected the following error,
However, when I loop through the children slice and validate each child struct as follows the test fails as expected,
Is there a straightforward way to do this validation of the items in a slice of structs?

Answer:

According to the documentation of the validator package, you can use dive in your struct tag to get this behavior. This causes the validator to also validate the nested struct/slice/etc.
So you would need to update your User struct to this:
Here it is working in Go Playground

If you have better answer, please add a comment about this, thank you!

go json slice struct validation
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: How do I use SetWindowText with Unicode in Win32 using PowerShell?

01/04/2023

Resolved: Shopware 400 Status Error “This value is too long. It should have 255 character or less.” When I Try Updating Database Table

01/04/2023

Resolved: Using AWK to count multiple patterns in a file

01/04/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.