validate

package
v0.17.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 5, 2026 License: MIT Imports: 5 Imported by: 0

Documentation

Overview

Package validate checks a struct by its `validate:` tags (github.com/go-playground/validator) and reports the failures as an errs.FieldErrors error.

It is a package of its own so that errs stays on the standard library: only a package that validates by tags builds the validator. A service that checks its input by hand collects the failures in errs.FieldErrors directly, and its client gets the same response.

Usage

type CreateReq struct {
    Name      string `json:"name" validate:"required,max=100"`
    CreatedAt string `json:"created_at" validate:"required"`
}

if err := validate.Check(req); err != nil {
    return err // 400: one entry per failed constraint in "fields"
}

Field names

A field is named as the client sends it: by its json tag, else its query tag, else its Go name in lower case. A nested field carries its path: "items[0].name". The error of a field is the failed tag: "required", "max".

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Check

func Check(val any) error

Check validates val by its `validate:` struct tags. On failure it returns an InvalidArgument *errs.Error with one errs.FieldError per failed constraint; the error of a field is the failed tag ("required", "max"). On success it returns nil.

Example

Check reports every failed tag as a field of one InvalidArgument error, named as the client sends it.

package main

import (
	"fmt"

	"github.com/assanoff/skit/errs"
	"github.com/assanoff/skit/validate"
)

type lineItem struct {
	Name string `json:"name" validate:"required"`
}

type createOrder struct {
	Customer string     `json:"customer" validate:"required,max=10"`
	Items    []lineItem `json:"items" validate:"min=1,dive"`
}

// Check reports every failed tag as a field of one InvalidArgument error,
// named as the client sends it.
func main() {
	err := validate.Check(createOrder{
		Customer: "a very long name",
		Items:    []lineItem{{Name: "pen"}, {}},
	})

	body, _, _ := errs.From(err).Encode()
	fmt.Println(errs.From(err).HTTPStatus())
	fmt.Println(string(body))
	fmt.Println(validate.Check(createOrder{Customer: "acme", Items: []lineItem{{Name: "pen"}}}))
}
Output:
400
{"code":"invalid_argument","title":"data validation error","detail":"validation failed","fields":[{"field":"customer","error":"max"},{"field":"items[1].name","error":"required"}]}
<nil>

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL