Skip to content
Projets

À propos

A Go library for validating structs, maps and slices.

Outils de développement

Comment ces chiffres sont mesurés

What you can do

  • Simple Simple and stupid, no magic involved.
  • Type-safe Schema is defined in Go, which is type-safer (and more powerful) than traditional struct tags.
  • Validators are composable.
  • Nested struct validation is well supported.

Progression mesurée des étoiles

in 24h
0
in 7 days
0
in 15 days
0
in 1 month
Historique en cours

Variations nettes sur des périodes qui se chevauchent, pas des totaux quotidiens. Les mesures absentes restent vides. Les étoiles indiquent l’intérêt, pas la qualité.

README.md

Original

validating

A Go library for validating structs, maps and slices.

Features

  1. Simple

    Simple and stupid, no magic involved.

  2. Type-safe

    Schema is defined in Go, which is type-safer (and more powerful) than traditional struct tags.

  3. Flexible

    • Validators are composable.
    • Nested struct validation is well supported.
    • Schema can be defined inside or outside struct.
    • Validator customizations are made easy.
  4. No reflection

Installation

$ go get github.com/RussellLuo/validating/v3@latest

Quick Start

package main

import (
	"fmt"

	v "github.com/RussellLuo/validating/v3"
)

type Address struct {
	Country string
	City    string
}

func (a Address) Schema() v.Schema {
	return v.Schema{
		v.F("country", a.Country): v.Nonzero[string]().Msg("empty country"),
		v.F("city", a.City):       v.In("A", "B", "C").Msg("must be A or B or C"),
	}
}

type Person struct {
	Name    string
	Age     int
	Hobbies []string
	Address Address
}

func (p Person) Schema() v.Schema {
	return v.Schema{
		v.F("name", p.Name): v.All(
			v.LenString(5, 10).Msg("bad name length"),
			v.Match(`\w+`).Msg("bad name pattern"),
		),
		v.F("age", p.Age):         v.Gte(10).Msg("must be at least 10 years old"),
		v.F("hobbies", p.Hobbies): v.EachSlice[[]string](v.In("Music", "Sports").Msg("unknown hobby")),
		v.F("address", p.Address): p.Address.Schema(),
	}
}

func main() {
	p := Person{
		Name:    "Foo",
		Age:     5,
		Hobbies: []string{"Nothing"},
		Address: Address{City: "D"},
	}
	errs := v.Validate(p.Schema())
	for _, err := range errs {
		fmt.Println(err)
	}
}
$ go run main.go
name: INVALID(bad name length)
age: INVALID(must be at least 10 years old)
hobbies[0]: INVALID(unknown hobby)
address.country: INVALID(empty country)
address.city: INVALID(must be A or B or C)

Validator factories and validators

To be strict, this library has a conceptual distinction between validator factory and validator.

A validator factory is a function used to create a validator, which will do the actual validation.

Built-in validator factories

Extension validator factories

Validator customizations

Examples

Documentation

Check out the Godoc.

Thanks

This library borrows some ideas from the following libraries:

License

MIT

Explorer des projets similaires

Chargement…