Validating struct fields made easy in GO language

Shivaraj arali
3 min readJan 8, 2019

--

In code it is often necessary to validate that a given value is valid before using it for something. but it can get significantly more complex, especially when dealing with structs. Package validator allows one to define valid values as struct tags when defining a new struct type.

Package validator provides build in functions like len, max, min, nonzero, regexp. I have defined three use cases on how to use validator package. The first step is to get this validator package and import it in the code.

go get gopkg.in/validator.v2import (
"gopkg.in/validator.v2"
)

Use Case 1: Testing default validation functionality provided in the package.

In this below example, structure NewU1Request has three fields with default tags provided by validator package. Lets validate them and verify the failure.

All the structure fields are obeying validate tag criteria except Age. Age should have value min=21 but provided value is 2. Hence failure is expected. Lets check the O/P.

Use Case 2: Providing custom validation function

In this below example, ValidateDeviceType() is the custom validation function provided for the structure tag “devicetype”. Here the test is, DeviceType field in the NewU2Request structure should have OLT or ONU as the value.

Using validator.SetValidationFunc(), we have provided custom ValidateDeviceType() function to validator object. Once default validator.Validate() is called, it checks for devicetype structure tag and invokes custom validate function. In our example, “HP-Server” is given for DeviceType which is not acceptable. Hence it should fail.

Note: Even we can supply parameters to custom validation function.

Use Case 3: Providing custom tag

Like “validate” tag, we can have single or multiple tags to a field in the structure. In below example, NewU3Request structure Players field has cricket and footbal custom tags. Ideally, for cricket number of players should be 11–15 and for footbal 7–11. Only one tag is provided at a time and corresponding tag criteria applies for validation.

Using validator.SetTag() method, we can provide our own custom tags. First tag is set as cricket, so it validates with min=11 and max=15. But provided value is 17 which is not acceptable. Second tag is set as footbal, so it validates with min=7, max=11. But provided value is 5 which is not acceptable.

Note: Validator package provided lot more provision like overwriting built in validate function, providing multiple validators and lot more. For more details refer https://godoc.org/gopkg.in/go-playground/validator.v2.

--

--