Nested Validation
The go-validator package supports nested validation , allowing you to define validation rules for fields within nested objects. This is particularly useful when working with complex JSON structures, such as user profiles with address details or order forms with product information.
How Nested Validation Works
- 
Define Nested Validation Rules - Use the Nestedfield in aValidationOptionto specify validation rules for nested objects.
- Each nested object can have its own set of ValidationOptionrules.
 
- Use the 
- 
Error Messages - When a validation fails, the error message returned is exactly the one specified by the developer in the Messagefield of theValidator.
- The package does not modify the error message to include the full path to the field. This ensures that the error messages remain simple and user-defined.
 
- When a validation fails, the error message returned is exactly the one specified by the developer in the 
- 
Recursive Validation - The Validatefunction automatically handles nested objects by recursively applying the validation rules.
 
- The 
Example: Validating a Nested Object
Below is an example of how to validate a nested object using the go-validator package.
Scenario
You want to validate a user object that contains an optional address field. The address field itself has two required fields: city and zipcode.
Code Example
Testing the Application
Step 1: Run the Application
Run the application using:
Step 2: Test with Valid Data
Send a valid POST request to the /user endpoint:
Expected response:
Step 3: Test with Invalid Data
Send an invalid POST request to the /user endpoint:
Expected response:
Key Takeaways
- 
Simple Error Messages - The error message returned is exactly the one specified by the developer in the Messagefield of theValidator.
- The package does not modify the error message to include the full path to the field.
 
- The error message returned is exactly the one specified by the developer in the 
- 
First Error Only - If multiple fields fail validation, the package returns the first error encountered. This ensures that the error response remains concise.
 
- 
Optional Nested Objects - Mark nested objects as optional using the IsOptionalfield.
 
- Mark nested objects as optional using the 
- 
Reusability - Nested validation rules are reusable and can be applied to multiple fields.
 
Advanced Example: Deeply Nested Objects
You can validate deeply nested objects by chaining multiple levels of Nested fields.
Scenario
You want to validate a user object that contains an address field, which itself contains a coordinates field with latitude and longitude.