DEV Community

Cover image for Adding JSON validation to structs in Go lang
Sanjay Singh Rajpoot
Sanjay Singh Rajpoot

Posted on

Adding JSON validation to structs in Go lang

In this blog, let's try to implement JSON validation for the data strut that we made. Let's start with the basics

What is JSON validation?

JSON validation verifies that the data that is fed into the struct is of the right order and value. This means that you can set rules and regulations for the data that is being placed into the struct object. The function or the library that we can use for this purpose is called JSON Validator. JSON Validator verifies that your JavaScript Object Notation adheres to the JSON specification. JSON Validator verifies that your JavaScript Object Notation adheres to the JSON specification.

below is an example of JSON validation

type Product struct {
    // the id for the product
    //
    // required: false
    // min: 1
    ID int `json:"id"` // Unique identifier for the product

    // the name for this poduct
    //
    // required: true
    // max length: 255
    Name string `json:"name" validate:"required"`

    // the description for this poduct
    //
    // required: false
    // max length: 10000
    Description string `json:"description"`

    // the price for the product
    //
    // required: true
    // min: 0.01
    Price float32 `json:"price" validate:"required,gt=0"`

    // the SKU for the product
    //
    // required: true
    // pattern: [a-z]+-[a-z]+-[a-z]+
    SKU string `json:"sku" validate:"sku"`
}
Enter fullscreen mode Exit fullscreen mode

What is the need for JSON validation?

There are a few reasons why JSON validation is important:

Data integrity: JSON validation helps ensure that the data in your JSON documents is accurate, complete, and consistent. By validating incoming JSON documents, you can catch errors and prevent invalid data from being processed by your application.

API consistency: If you're building an API that accepts JSON documents as input, JSON validation can help ensure that your API is consistent and predictable. By defining a schema for your JSON documents and validating incoming documents against that schema, you can ensure that your API receives the correct data and returns the expected results.

Security: JSON validation can also help improve the security of your application. By ensuring that your JSON documents are properly formatted and contain only valid data, you can prevent attacks such as injection attacks that might exploit vulnerabilities in your application.

Implementing JSON validation in GoLang
For JSON validation we will make use of a library called Validator v10.

Few Package validator features

  • Cross Field and Cross Struct validations by using validation tags or custom validators.

  • Slice, Array and Map diving, which allows any or all levels of a multidimensional field to be validated.

  • Ability to dive into both map keys and values for validation

  • Handles type interface by determining it's underlying type prior to validation.

  • Alias validation tags, which allows for mapping of several validations to a single tag for easier defining of validations on structs.

Installation

Use go get.




go get github.com/go-playground/validator/v10
Then import the validator package into your own code.



import "github.com/go-playground/validator/v10"
Enter fullscreen mode Exit fullscreen mode

Once that is done let's create a simple struct to accept a few values and assign

some parameters to it.

Go

type User struct {
    ID       int    `json:"id" validate:"required,gt=0"`
    Username string `json:"username" validate:"required,min=3,max=20"`
    Email    string `json:"email" validate:"required,email"`
}
Enter fullscreen mode Exit fullscreen mode

In this example, we've defined a User struct with three fields: ID, Username, and Email. We've also added validation tags to each field, which specify the validation rules that should be applied to each field.

For example, the ID field has a required and gt validation tag, which means it must be a required field and must be greater than 0. The Username field has a required and min and max validation tag, which means it must be a required field and must be at least 3 characters long and at most 20 characters long. The Email field has a required and email validation tag, which means it must be a required field and must be a valid email address.

After this inside the main function create a new object of the Validator class and call its Struct() method. Passing it the JSON string and a pointer to a struct that represents the document. If the validation fails, the function returns an error containing a list of validation errors for each field that failed validation. If the validation succeeds, the function returns nil.

Entire code

package main


import (
    "fmt"
    "strings"

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

type User struct {
    ID       int    `json:"id" validate:"required,gt=0"`
    Username string `json:"username" validate:"required,min=3,max=20"`
    Email    string `json:"email" validate:"required,email"`
}

func main() {
    jsonStr := `{"id": 1, "username": "user", "email": "user@example.com"}`
    var user User
    validate := validator.New()
    if err := validate.Struct(jsonStr, &user); err != nil {
        errs := err.(validator.ValidationErrors)
        for _, fieldErr := range errs {
            fmt.Printf("field %s: %s\n", fieldErr.Field(), fieldErr.Tag())
        }
        return
    }
    fmt.Println("validation succeeded")
}
Enter fullscreen mode Exit fullscreen mode

Thank You for reading!!

bye :)
type User struct {
ID int json:"id" validate:"required,gt=0"
Username string json:"username" validate:"required,min=3,max=20"
Email string json:"email" validate:"required,email"
}

func main() {
jsonStr := {"id": 1, "username": "user", "email": "user@example.com"}
var user User
validate := validator.New()
if err := validate.Struct(jsonStr, &user); err != nil {
errs := err.(validator.ValidationErrors)
for _, fieldErr := range errs {
fmt.Printf("field %s: %s\n", fieldErr.Field(), fieldErr.Tag())
}
return
}
fmt.Println("validation succeeded")
}
Thank You for reading!!

bye :)

Top comments (0)