gofiber-validator-middleware is a gofiber middleware to generate a go-playground/validator singleton for use in validating DTOs in handlers (or whatever you need to validate).
go get github.com/rgglez/gofiber-validator-middlewareNextdefines a function to skip this middleware when returned true.Validatorinjected instance, if nil a new validator will be created.ContextKeyis the key used to store the validator in context. Optional. Default: "validator"CustomValidationsallows you to register custom validation functions. Optional. Default: nil
import (
gofibervalidator "github.com/rgglez/gofiber-validator-middleware/gofibervalidator"
)
// Custom validation function example
func isEvenNumber(fl validator.FieldLevel) bool {
value := fl.Field().Int()
return value%2 == 0
}
app.Use(gofibervalidator.New(gofibervalidator.Config{
ContextKey: "validator",
CustomValidations: map[string]validator.Func{
"even": isEvenNumber,
},
Next: func(c *fiber.Ctx) bool {
// Skip validation for specific routes
return c.Path() == "/health"
},
}))An example is included in the example directory. To execute it:
- Enter the example directory.
- Run the example:
go run . - You can try 3 use cases:
- Skip validation (GET): http://127.0.0.1:3000/health
- Validate user "creation" (POST): http://127.0.0.1:3000/users
- Validate product "creation" (POST): http://127.0.0.1:3000/products
You can use resting or the plugin of your choice, or tools like curl, to try the endpoints.
Run the tests with:
go test ./gofibervalidator/... -v| Test | What it verifies |
|---|---|
TestNew_DefaultConfig |
Middleware stores a *validator.Validate under the "validator" key by default |
TestNew_CustomContextKey |
Custom ContextKey is used; default key is absent |
TestNew_EmptyContextKeyFallsBackToDefault |
Empty ContextKey falls back to "validator" |
TestNew_NextSkipsMiddleware |
When Next returns true, middleware is skipped and no validator is stored |
TestNew_CustomValidatorInstance |
A pre-built *validator.Validate provided via config is used as-is |
TestNew_CustomValidations |
Custom tag functions registered via CustomValidations work correctly |
TestGetValidator_DefaultKey |
GetValidator retrieves the instance using the default key |
TestGetValidator_CustomKey |
GetValidator retrieves via a custom key; wrong key returns nil |
TestGetValidator_NotInContext |
GetValidator returns nil when no middleware is registered |
TestGetValidator_ValidatesStruct |
The retrieved validator correctly validates struct fields |
Copyright (c) 2026 Rodolfo González González.
Licensed under the Apache 2.0 license. Read the LICENSE file.