Validating Go Structs Using Govalidator

Structs are one of the primary and popularly used data types provided in the Go programming language. Many packages across various functionalities, from database packages to ORMs, and some web frameworks use structs for easy data parsing and other operations.

Struct validation is a common task in Go, and the Go validator package provides a simple and efficient way to validate structs in your projects.

What Is the Go Validator Package

github preview for the validator package

The Go validator package implements value validations for struct and individual fields based on specified tags on struct declaration.

The Go validator package provides features for cross-field and cross-struct validation using tags, slice, array, and map diving that allow levels of multidimensional field validation, custom field validation, extraction of custom-defined field names, customizable error messages, and support for the popular Gin framework as the default validator for the package.

Run one of these commands in the terminal of your working directory to install the validator package.

 go get
go get

The versions are the suffix of the URL. The first command installs version 9, and the second installs version 10 of the package.

After installing the package, you can import the package into your projects depending on the version you installed.

 import (

You can now proceed to use the Go validator package. If there are any issues with your installation, try reinstalling/upgrading to the latest Go version.

Validating Structs With the Validator Package

You’ll need to create an instance of the validator.Validate struct, define the struct you want to validate using validation tags to specify the validation rules for the fields.

Here’s how you can create an instance of the validator.Validate struct.

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

You can define a struct you want to validate by specifying tags for the fields, thereby setting validation rules. Validation tags are special annotations of struct field definitions that specify the rules.

Here’s a regular struct for validation.

 type User struct {
    Name string
    Age int
    Email string

Here’s an example of the struct, ready for validation.

 type User struct {
    Name string `validate:"required"`
    Age int `validate:"gte=0,lte=130"`
    Email string `validate:"required,email"`

In this example, you specified the Name field as required on instantiation, the Age field must be greater than or equal to 0 and less than or equal to 130, and the Email field is required and must be a valid email address on instantiation.

Different validation tags are available in the Go validator package, including tags for required fields, minimum and maximum values, and regular expressions. You can find a complete list of the available validation tags in the documentation for the Go validator package.

Once you have defined the struct you want to validate and specified the validation rules for each field, you can use the Struct method of the validator.Validate struct to validate the struct.

 user := User{
    Age: 3990000,
    Email: "",

err := validate.Struct(user)
if err != nil {

The Struct method returns an error if validation errors exist, and you can handle the error based on your operation.

You can access these errors using the ValidationErrors method of the error.

 if err != nil {
    for _, err := range err.(validator.ValidationErrors) {
        fmt.Println(err.Field(), err.Tag())

The ValidationErrors method will return the name of each field with a validation error and the validation tag that caused the error.

error output

You can also define custom validation tags if specific validation requirements aren’t part of the built-in tags.

You can use the RegisterValidation method of the validator.Validate struct. The RegisterValidation method takes two arguments; the name of the validation tag and a validation function. The validation function is a callback function that gets called for each field having the custom validation tag, and the function must return true if the field is valid and false if otherwise.

Here’s an example definition of a custom validation tag. The tag validates fields for even numbers.

 validate.RegisterValidation("even", func(fl validator.FieldLevel) bool {
    value, ok := fl.Field().Interface().(int)
    if !ok {
        return false
    return value % 2 == 0

The code defines a custom validation tag even using the RegisterValidation method of the validator.Validate struct. You defined the validation tag using a function that takes a single argument of type validator.FieldLevel.

You can now use the custom validation tag in struct definitions the same way you would for built-in validation tags.

 type MyStruct struct {
    Value int `validate:"even"`

There’s More to Go Structs

Structs are first-class citizens in Go, and there’s so much you can do with structs. If you’re familiar with purely object-oriented languages, you can use Go structs to operate on data as you would with classes.

Source link


Leave a Reply

Your email address will not be published. Required fields are marked *