verrors provides structured validation errors for Go applications using
go-playground/validator.
It converts validator failures into JSON-aware field errors suitable for APIs.
Instead of returning raw validator errors containing Go struct names and
unstructured messages, verrors returns predictable field errors that match the
JSON structure of the request.
Example output:
[
{
"field": "user.address.street",
"message": "field is required"
}
]go get github.com/iamonah/verrorsimport verrors "github.com/iamonah/verrors"
type CreateUserRequest struct {
Email string `json:"email" validate:"required,email"`
Password string `json:"password" validate:"required,min=8"`
}
req := CreateUserRequest{
Email: "",
Password: "123",
}
err := verrors.Validate(req)
if err != nil {
return err
}Validation error:
[
{
"field": "email",
"message": "field is required"
}
]verrors resolves nested validation errors using JSON field paths.
type Address struct {
Street string `json:"street" validate:"required"`
}
type User struct {
Email string `json:"email" validate:"required,email"`
Address Address `json:"address"`
}
type CreateUserRequest struct {
User User `json:"user"`
}Validation result:
[
{
"field": "user.email",
"message": "field is required"
},
{
"field": "user.address.street",
"message": "field is required"
}
]Slice elements include the failing index.
type Item struct {
ProductID string `json:"product_id" validate:"required"`
}
type CreateOrderRequest struct {
Items []Item `json:"items" validate:"required,dive"`
}Result:
[
{
"field": "items[0].product_id",
"message": "field is required"
}
]func Validate(data any) errorValidates a struct using go-playground/validator.
This is the main entry point for the package.
func ValidateStruct(data any) errorValidateStruct behaves the same as Validate.
Validate is a small convenience wrapper around it.
Returns:
nilif validation succeedsFieldErrorsif validation fails- the underlying error if validation cannot be interpreted
type FieldError struct {
Field string `json:"field"`
Message string `json:"message"`
}type FieldErrors []FieldErrorFieldErrors implements the error interface and can be returned directly.
Applications may inspect validation errors using errors.As.
import (
"errors"
"fmt"
verrors "github.com/iamonah/verrors"
)
req := CreateUserRequest{
Email: "",
Password: "123",
}
err := verrors.Validate(req)
if err != nil {
var fields verrors.FieldErrors
if errors.As(err, &fields) {
for _, f := range fields {
fmt.Println(f.Field, f.Message)
}
}
}The package provides formatted messages for common validator tags.
requiredemailminmaxlenoneofgtgteltlte
Unknown tags fall back to the validator's default message.
verrors focuses on one responsibility:
converting validator failures into structured field errors.
The package does not enforce any particular API response format. Applications remain free to wrap validation errors however they choose.
MIT