
Golang's built-in validation package is a must-have for any Go developer. It's a powerful tool that helps you validate user input and ensure your application remains secure.
The validator package is a part of the standard library, making it easily accessible and convenient to use. This means you don't have to worry about adding extra dependencies to your project.
With the validator package, you can validate various types of input, including strings, integers, and structs. It provides a simple and efficient way to check if input conforms to specific rules.
Installation
To install the golang validator, you'll need to use the go get command.
This command will download and install the package for you.
Getting Started
To use go-validator, you need to install the package first. This is a straightforward process that will get you up and running with the tool.
The installation process is where many people can get stuck, but don't worry, it's easy. You just need to follow the instructions and you'll be good to go.
In the example, validation will fail because the age is less than 18, so make sure to test your installation thoroughly. This will ensure that everything is working as expected.
Go
Installing Go is a straightforward process, and you can start by downloading the Go installer from the official Go website.
The Go installer is available for Windows, macOS, and Linux, making it accessible to a wide range of users.
To get started with Go, you'll need to install the Go compiler and the Go toolchain.
The Go compiler is a key component of the Go toolchain, and it's responsible for compiling your Go code into executable files.
Here are the key components of the Go toolchain:
- Go compiler (go tool): responsible for compiling Go code
- Go linker (go tool): responsible for linking compiled code into executable files
- Go toolchain (go tool): a collection of tools for building, testing, and running Go programs
Error Handling
=====================================
Error handling is a crucial aspect of any validation process, and Go Validator makes it a breeze. The error returned by validation functions is of type "error", which helps avoid the issue of always having a non-nil error.
To check if the error is not nil, you can use a simple if statement. If the error is not nil, you can then check if it's an InvalidValidationError, and if so, type cast it to ValidationErrors.
A different take: Golang Types
Here's an example of how to do this:
```html
- http://stackoverflow.com/a/29138676/3158232
- https://github.com/go-playground/validator/issues/134
```
By using this approach, you can extract detailed information about each error using the FieldError structures provided by the error returned by validation functions.
Go Validator also offers a robust way to validate data in Go applications, making it an essential tool in every Go developer's toolkit. Always ensure that you have other security measures in place, especially when dealing with user-generated data.
Validator Basics
The Go Validator package is a powerful tool for input validation in Go applications. It provides a wide range of features for validating data, including cross-field and cross-struct validations.
One of the unique features of the Go Validator package is its ability to dive into arrays and maps of any type, making it a versatile tool for handling complex data structures. This feature is particularly useful when working with nested structs.
Here are some key features of the Go Validator package:
- 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
Introduction
Input validation is crucial for data integrity and security in any software application. Go's "validator" package (v10) offers efficient validation.
Go's validator package is known for its simplicity and performance, making it a popular choice among developers.
Data validation is like checking if the keys fit before opening a door, ensuring that the information we get from users is safe and correct.
Without proper validation, websites could become vulnerable to sneaky attacks from hackers, which is why it's essential to implement validation in our applications.
Go's validator package can handle Cross-Field and Cross-Struct validation for nested structs and has the ability to dive into arrays and maps of any type.
Basic Usage
Go Validator is an open-source package that provides a way to use tags on struct fields to specify validation rules.
You can enforce rules like "required", "minimum length", "email format", and many more directly in the data structure definition. This is similar to how the standard library does it, as seen in the file.Open method.

The Validator package, part of the go-common library, builds on validator/v10 and provides tools to make input validation more flexible, customizable, and easier to manage. It’s particularly useful if you often create custom validation rules or need more control over error messages and field naming.
To get started with Go Validator, you can use the GitHub repository for the go-common library, which provides a user-friendly API for struct validation. You can also check out the example code on GitHub, which demonstrates how to easily check and handle user input using Go with Fiber and the go-playground/validator package.
Here's a simple example of how to use Go Validator to validate a User struct:
Register Tag Name
The RegisterTagNameFunc function registers a function to get alternate names for StructFields.
This function is particularly useful when working with JSON representations of structs, allowing you to use the names specified for JSON instead of the normal Go field names.

To register a function, you can use the RegisterTagNameFunc method, which is not thread-safe, so it's intended that these all be registered prior to any validation.
Here's a simple example of how you can use this function to get alternate names for StructFields:
By using this function, you can simplify your validation process and make it more flexible and customizable.
Validator Package
The Go Validator package is a powerful tool for validating input parameters in Go. It's a package that implements value validations for structs and individual fields based on tags.
Go Validator V10 is the version we'll be using in this example, and it's a significant improvement over previous versions. It has a lot of unique features that make it a great choice for validation.
The package has a wide range of features, including cross field and cross struct validations, slice and array diving, and the ability to dive into both map keys and values for validation. It also handles type interface by determining its underlying type prior to validation, and has customizable i18n aware error messages.
Here are some of the key features of the Go Validator package:
- 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.
- Handles custom field types such as sql driver Valuer see Valuer
- Alias validation tags, which allows for mapping of several validations to a single tag for easier defining of validations on structs
- Extraction of custom defined Field Name e.g. can specify to extract the JSON name while validating and have it available in the resulting FieldError
- Customizable i18n aware error messages.
Import Package
The validator package is imported using the `import` keyword followed by the package name. In this case, it's `github.com/go-playground/validator/v10`.
Package Validator
The Package Validator is a powerful tool in the Validator Package. It implements value validations for structs and individual fields based on tags.
One of its unique features is Cross Field and Cross Struct validations by using validation tags or custom validators. This allows for complex validation rules to be applied across multiple fields and structs.
The Package Validator also has features like Slice, Array and Map diving, which allows any or all levels of a multidimensional field to be validated. This is useful for validating complex data structures.
It can also dive into both map keys and values for validation, making it a versatile tool for input validation. This is particularly useful for validating data from external sources.
The Package Validator can handle type interface by determining its underlying type prior to validation. This ensures that the validation rules are applied correctly, even for complex data types.
It can also handle custom field types such as sql driver Valuer. This makes it a great tool for validating data in databases.
The Package Validator has alias validation tags, which allows for mapping of several validations to a single tag for easier defining of validations on structs. This can simplify the validation process and make it more efficient.
Here are some of the key features of the Package Validator:
- Cross Field and Cross Struct validations
- Slice, Array and Map diving
- Map key and value validation
- Type interface handling
- Custom field type handling
- Alias validation tags
- Customizable i18n aware error messages
Register Translation
Registering translations is a crucial step in ensuring your validator package is accessible to a global audience. The RegisterTranslation function is used to register translations against a provided tag.
This function allows you to specify the translations for a particular tag, making it easy to switch between languages. The RegisterTranslation function is part of the Validate package.
Defining Data
To define a data structure in Go, you start by creating a struct that represents the data you expect to receive. This struct can have multiple fields, each with its own validation rules.
For example, a User struct might have fields like Username, Email, and Age, where each field has specific validation rules. You can use validation tags from Go Validator V10 to specify these rules.
Go Validator V10 provides a comprehensive list of supported validation tags, which you can find in its official documentation at https://pkg.go.dev/github.com/go-playground/validator/v10.
Define Data
To define data, you can use a Go struct to represent the data structure of the input you expect to receive.
A User struct with three fields Username, Email, and Age is a good example of a data structure you might define. This struct can be used to validate incoming data.
You can add validation tags using Go Validator V10 syntax to specify the validation rules for each field. For instance, you might use a validation tag to ensure that the Username field is not empty.
The official documentation of Go Validator V10 at https://pkg.go.dev/github.com/go-playground/validator/v10 provides a full list of supported validation tags and their usage.
Struct validation in Go is a useful tool for automatically validating nested structs. This can be achieved using the (*Validate) Struct function, which returns an InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise.
Step 3: Input
Input is crucial for any data-driven application, and validating it is essential to ensure accuracy and prevent errors.
We've established that input parameters should be validated, as seen in the example of a simple API endpoint that receives data in JSON format.
To validate input, you first need to parse the incoming JSON data and populate a struct, such as the User struct mentioned in the code snippet.
Next, create a new validator instance and use it to validate the populated struct using a function like validate.Struct(user).
If validation fails, the error message with specific validation errors will be returned, allowing you to address the issues before proceeding.
Validator Rules
Validator Rules are an essential part of ensuring the accuracy and security of your data processing. Go Validator V10 provides a wide range of built-in validation rules, including alpha, alphanumeric, and boolean checks.
You can also create custom validators to enforce domain-specific rules on your data. For example, you can create a PercentageValidator that checks whether the input value represents a valid percentage (ranging from 0 to 100).
Go Validator V10 supports various data types, including strings, integers, and floats. It also allows you to dive into both map keys and values for validation, making it a powerful tool for data validation.
Here are some of the built-in validation rules provided by Go Validator V10:
You can also use comparison tags, such as eq, eq_ignore_case, gt, gte, lt, lte, ne, and ne_ignore_case, to validate the equality or inequality of values.
Validator Rules
Validator Rules are the backbone of any robust validation system. They determine what constitutes valid input and what doesn't. You can define various rules using tags, which are attached to the fields you want to validate.
Some common validation rules include checking for alphabetic, alphanumeric, or numeric characters. For example, the "alpha" tag validates that a string value contains only alphabetic characters. Similarly, the "alphanumeric" tag ensures that a string value contains only alphanumeric characters. You can use these tags to validate fields like usernames, passwords, or email addresses.
Here's a list of some common validation rules and their corresponding tags:
You can also use more complex rules, like checking if a string value starts or ends with a certain substring. For instance, the "startswith" tag ensures that a string value starts with a specific substring. Similarly, the "endswith" tag checks if a string value ends with a specific substring.
Validator rules can be combined to create more complex validation logic. For example, you can use the "required" tag along with the "email" tag to ensure that an email address is both required and valid. You can also use custom validators to define more complex rules that don't fit into the standard set of validation rules.
In addition to these rules, you can also use validation tags to specify additional constraints on the input data. For example, the "min" and "max" tags can be used to specify the minimum and maximum allowed values for a numeric field. Similarly, the "minlen" and "maxlen" tags can be used to specify the minimum and maximum allowed lengths for a string field.
Base64 String
A valid base64 string is a string value that contains a valid base64 value.
You might be surprised to know that an empty string is technically a valid base64 value, but this validator will still report it as an error.
If you want to accept empty strings as valid, you can use the omitempty tag with this validator.
This will allow the validator to ignore empty strings and only report errors for invalid base64 values.
See what others are reading: Golang Base64
Custom Validators
Go-validator comes with many built-in validations, but there may be instances when you need custom validation rules.
You can create custom validators tailored to your specific application requirements, allowing you to enforce domain-specific rules on your data.
For example, you can create a custom validator named PercentageValidator that checks whether the input value represents a valid percentage (ranging from 0 to 100).
To use this custom validator, you need to register it with Go Validator V10 before performing input validation.
You can register it in the following way, and then apply the percentage validation tag to any field that requires percentage validation in your User struct or any other data structure.
By creating custom validators, you can tailor the input validation to your specific application's needs, ensuring the accuracy and security of your data processing.
Custom validation functions can be added, and you can even use cross-fields validation tags, like eqcsfield.
Non-standard validators are also available, which are frequently needed but are more complex than the built-in validators.
To use a non-standard validator, you need to register it manually like you would with your own custom validation functions.
Go-validator allows for custom validation functions, and you can create custom validators to ensure that the number is odd, for example.
You can also register a mapping of a single validation tag that defines a common or complex set of validation(s) to simplify adding validation to structs, using the RegisterAlias function.
This function is not thread-safe, so it's intended that these all be registered prior to any validation.
Validator Usage
To use the Go Validator, you can visit the official documentation at http://godoc.org/gopkg.in/go-playground/validator.v9 for detailed usage docs. This page lists various features, including Simple, Custom Field Types, Struct Level, Translations & Custom Errors, Gin upgrade and/or override validator, and wash - an example application putting it all together.
The Go Validator can be used to validate input parameters for a simple API endpoint that receives data in JSON format. For example, you can validate that the FirstName and LastName fields are required, the Email field must be a valid email address, and the Age field must be greater than or equal to 18.
Here are some key features of the Go Validator:
- Simple: Validates basic types such as strings, integers, and booleans.
- Custom Field Types: Allows you to create custom validation rules for specific types.
- Struct Level: Validates entire structs, not just individual fields.
- Translations & Custom Errors: Provides options for customizing error messages and translations.
Usage and Documentation
The package validator is a powerful tool, and understanding how to use it effectively is crucial for any serious developer. You can find detailed usage documentation at http://godoc.org/gopkg.in/go-playground/validator.v9.
To get started with the package validator, you can check out the simple usage example. The package validator also supports custom field types, which is a game-changer for complex data validation.

One of the most useful features of the package validator is its ability to handle cross-field and cross-struct validations. This is achieved through the use of validation tags or custom validators.
The package validator also provides a default validator for the gin web framework, making it a great choice for developers using this framework. This is especially useful for those upgrading from v8 to v9 in gin.
For a more comprehensive look at the package validator's capabilities, check out the detailed documentation. The package validator supports a range of features, including:
- Simple
- Custom Field Types
- Struct Level
- Translations & Custom Errors
- Gin upgrade and/or override validator
- wash - an example application putting it all together
The package validator's flexibility and customizability make it a top choice for developers. With its support for i18n aware error messages and customizable validation tags, you can tailor the package validator to fit your specific needs.
Go-Playground
Go-Playground is a great tool for testing and exploring the validator. It's where you can see your validation working as expected.
You can see that the validation is indeed working, but there's an issue with the validation message. It's not displaying correctly.
Advanced Topics
In Go, you can use the `github.com/go-playground/validator/v10` package to validate structs. This package provides a simple and efficient way to validate data.
The `Validate` method is used to validate a struct, and it returns an error if the validation fails. For example, if you have a struct like `type User struct { Name string `validate:"required"` }`, the `Validate` method will return an error if the `Name` field is empty.
Tagging fields with a specific validation rule allows you to customize the validation process. For instance, if you have a field like `type User struct { Email string `validate:"email"` }`, the `Validate` method will check if the email address is valid according to the standard email format.
Context and Filtering
Context and Filtering is a powerful feature of the GoLang Validator. It allows you to filter fields using the StructFiltered function, which returns true if the field is filtered or skipped from validation.
You can use the FilterFunc type to specify which fields to filter. This is useful when you have a large struct with many fields and you only want to validate a subset of them.
The StructFilteredCtx function is similar to StructFiltered, but it also allows passing of contextual validation information via context.Context. This can be useful when you need to validate fields based on additional information.
You can also use the StructPartialCtx function to validate only the fields that are passed in, ignoring all others. This is useful when you have a complex struct with many fields and you only want to validate a specific subset of them.
Here's a brief overview of the functions mentioned:
The StructPartial and StructPartialCtx functions allow you to specify fields in a namespaced fashion relative to the struct provided. This can be useful when you have a complex struct with many nested fields.
The FuncCtx type accepts a context.Context and FieldLevel interface for all validation needs. The return value should be true when validation succeeds, and an error returns an InvalidValidationError message.
License

The license for the GoLang Validator is the MIT License, which you can find in the license file within the code.
This license is open-source, allowing for free use, modification, and distribution of the code.
The MIT License is a permissive license that allows for a wide range of uses, including commercial and non-commercial projects.
Here are some key points about the MIT License:
- Allows for free use and distribution of the code
- Permits modification and derivative works
- Requires attribution to the original authors
Overall, the MIT License provides a flexible and widely-used framework for open-source projects like the GoLang Validator.
Featured Images: pexels.com


