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.

4

What Is the Go Validator Package

TheGo validatorpackage 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 popularGin frameworkas the default validator for the package.

Hand holding a phone showing the Basmo reading app’s first page

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

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

GIMP website on a monitor.

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

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

Several laptops side by side with different Linux distributions.

Validating Structs With the Validator Package

You’ll need to create an instance of thevalidator.Validatestruct, 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 thevalidator.Validatestruct.

The Go mascot

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.

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

In this example, you specified theNamefield as required on instantiation, theAgefield must be greater than or equal to 0 and less than or equal to 130, and theEmailfield 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, andregular 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, it’s possible to use theStructmethod of thevalidator.Validatestruct to validate the struct.

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

You can access these errors using theValidationErrorsmethod of the error.

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

Defining Custom Validation Tags

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

you’re able to use theRegisterValidationmethod of thevalidator.Validatestruct. TheRegisterValidationmethod 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 returntrueif the field is valid andfalseif otherwise.

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

The code defines a custom validation tagevenusing theRegisterValidationmethod of thevalidator.Validatestruct. You defined the validation tag using a function that takes a single argument of typevalidator.FieldLevel.

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

There’s More to Go Structs

Structs are first-class citizens in Go, and there’s so much you may 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.

Getting to grips with object oriented programing in Go isn’t as tough as you think.

Every squeak is your PC’s way of crying for help.

You’ve been quoting these famous films wrong all along!

Sometimes the smallest cleaning habit makes the biggest mess.

Tor spoiled me forever.

I plugged random USB devices into my phone and was pleasantly surprised by how many actually worked.

Technology Explained

PC & Mobile