Go Validator

Installation

GitHub Repository

go-validator is an open-source project. You can find the source code and contribute to the project on GitHub:

1. Installation Guide

Install the latest version of go-validator via:

go get github.com/kthehatter/go-validator/validator

For Gin framework integration, also install the Gin adapter:

go get github.com/kthehatter/go-validator/validator/ginadapter

Note: Ensure you are using Go 1.18+ for compatibility.

2. Core Concepts

Introduce the core components of the package and their roles.

ValidationOption

Defines the validation rules for a specific field in the object to be validated e.g. the request body.

  • Fields:
    • Key: The name of the field in the request body.
    • IsOptional: Whether the field is optional.
    • Validators: A list of validators to apply to the field.
    • Transformers: A list of transformers to modify the field's value.
    • Nested: Validation rules for nested objects.

Validator

Represents a single validation rule.

  • Fields:
    • Func: The validation function.
    • Message: The error message to return if validation fails.

Transformer

A function that modifies the value of a field before validation.

Validate Function

The main function used to validate a request body against a set of ValidationOption.

func Validate(body map[string]interface{}, options []ValidationOption) error

On this page