42 lines
1.7 KiB
Go
42 lines
1.7 KiB
Go
// Package validate provides small, composable value validators.
|
|||
|
|
//
|
||
|
|
// A validator is just a func(T) error: it returns nil when the value is
|
||
|
|
// acceptable, or an error describing the problem. Nothing has to implement
|
||
|
|
// an interface, so a plain closure works anywhere a validator is expected.
|
||
|
|
// Combine validators with [All] (stop at the first failure) or [Collect]
|
||
|
|
// (run them all and join every failure).
|
||
|
|
//
|
||
|
|
// username := validate.All(
|
||
|
|
// validate.MinLength(3),
|
||
|
|
// validate.MaxLength(16),
|
||
|
|
// validate.Chars("abcdefghijklmnopqrstuvwxyz0123456789_"),
|
||
|
|
// )
|
||
|
|
// if err := username(input); err != nil {
|
||
|
|
// // errors.Is(err, validate.ErrDisallowedChars) still works here
|
||
|
|
// }
|
||
|
|
//
|
||
|
|
// Errors are plain sentinel values (see [Error]); match them with
|
||
|
|
// errors.Is. [Err] matches any error produced by this package.
|
||
|
|
//
|
||
|
|
// # Comparison with other packages
|
||
|
|
//
|
||
|
|
// - go-playground/validator drives validation from struct tags and
|
||
|
|
// reflection.
|
||
|
|
// - go-ozzo/ozzo-validation composes rules in code, but through a Rule
|
||
|
|
// interface over interface{}.
|
||
|
|
// - asaskevich/govalidator is a bag of IsX string helpers.
|
||
|
|
//
|
||
|
|
// This package is the code-composition style with two constraints kept
|
||
|
|
// deliberately: validators are ordinary generic functions, checked by the
|
||
|
|
// compiler with no reflection ([In], [Equal] and the rest will not accept
|
||
|
|
// the wrong type), and there are no dependencies outside the standard
|
||
|
|
// library.
|
||
|
|
//
|
||
|
|
// # When to use something else
|
||
|
|
//
|
||
|
|
// Reach for go-playground/validator if you want struct-tag validation,
|
||
|
|
// translated messages, or a large catalogue of built-in checks. This
|
||
|
|
// package stays small and leaves struct/field wiring and error
|
||
|
|
// presentation to the caller.
|
||
|
|
package validate
|