Sling Academy
Home/Golang/Data Validation and Sanitization with `validator` in Go

Data Validation and Sanitization with `validator` in Go

Last updated: November 27, 2024

Data validation and sanitization are fundamental processes in any application development to ensure कि input data is consistent, correct, and secure before processing it further. In the Go programming language, the `validator` package provides a convenient way to validate and sanitize your data.

Introduction to the `validator` package

The `validator` package in Golang provides a rich set of functionality to validate and tag struct fields using simple annotations. It serves as a comprehensive library for performing checks like length, format, inclusion in a collection, and much more. It's helpful to enforce constraints on your data, ensuring that the inputs remain clean and predictable.

Installing the `validator` package

To start using the `validator` package in your project, first ensure it's installed. You can do this using the following command:

go get github.com/go-playground/validator/v10

Basic Usage

Building a struct validation in Go typically involves tagging your struct fields with validation rules. Here's a basic example:


package main

import (
    "fmt"
    "github.com/go-playground/validator/v10"
)

type User struct {
    Name  string `validate:"required"`
    Email string `validate:"required,email"`
    Age   int    `validate:"gte=18,lte=120"`
}

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

    user := User{
        Name:  "",
        Email: "invalid-email",
        Age:   17,
    }

    if err := v.Struct(user); err != nil {
        for _, err := range err.(validator.ValidationErrors) {
            fmt.Printf("%s is not valid: %s\n", err.Field(), err.Tag())
        }
    }
}

In this example, the `User` struct has some simple validation rules defined using struct field tags:

  • required makes sure the field is not omitted.
  • email ensures the email format is correct.
  • gte=18,lte=120 establishes an age constraint where values should be between 18 and 120.

Advanced Validation Rules

`validator` provides numerous built-in tags for validation, and you can easily create custom ones if needed. Here’s how you can use more advanced built-in tags:


type Order struct {
    ProductID   string  `validate:"alphanum"`
    Quantity    int     `validate:"gt=0"`
    Price       float64 `validate:"required,gt=0"`
    OrderNotes  string  `validate:"max=255"`
}

In this `Order` struct:

  • alphanum allows only alphanumeric values in ProductID.
  • gt=0 ensures that Quantity and Price must be greater than 0.
  • max=255 limits OrderNotes to not exceed 255 characters.

Custom Validation Functions

If your application demands specific validation logic beyond what the built-in functions offer, you can register custom validation functions:


func registerCustomValidations(v *validator.Validate) {
    v.RegisterValidation("is-awesome", func(fl validator.FieldLevel) bool {
        return fl.Field().String() == "awesome"
    })
}

func main() {
    v := validator.New()
    registerCustomValidations(v)

    type Custom struct {
        Opinion string `validate:"is-awesome"`
    }

    c := Custom{Opinion: "boring"}

    if err := v.Struct(c); err != nil {
        for _, err := range err.(validator.ValidationErrors) {
            fmt.Printf("%s: %s\n", err.Field(), err.Error())
        }
    }
}

This example shows how to validate that a field must contain the word "awesome" using a custom tag is-awesome.

Conclusion

Using the validator package in Go is a robust way to ensure that your application data is valid and properly structured before it makes its way further into your system. This package boosts both security and robustness in data handling. Whether you are validating complex struct inputs or need customizable rules, validator offers a comprehensive solution.

Next Article: How to Create and Handle ZIP Files in Go with `archive/zip`

Previous Article: Exploring Go's `context` Package for Better Concurrency Control

Series: Go Utilities and Tools

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant