Documentation
¶
Overview ¶
Package valid provides declarative, type-safe struct validation. A field is a name, a value, and a list of rules; a rule is just `func(T) error`, so any custom validator is a first-class rule with no wrapper:
func (in CreateInput) Validate() valid.Problems {
return valid.Validate(
valid.String("name", in.Name, valid.Required, valid.MinLength(3)),
valid.String("host", in.Host, valid.Required, isSubdomain), // isSubdomain: func(string) error
valid.Number("ttl", in.TTL, valid.Required, valid.Max(100)),
valid.Slice("values", in.Values, valid.NotEmpty, valid.Each(isIPv4)),
)
}
Type safety comes from the per-type constructors: String only accepts Rule[~string], Number only Rule[number], Slice only Rule[[]T] — so a string rule cannot be attached to a number field, and Each([]T)'s element rules are keyed to the element type.
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Required ¶
func Required[T comparable](v T) error
Required asserts a comparable value is not its zero value (empty string, zero number, zero-value enum). For slices use NotEmpty.
Types ¶
type Field ¶
Field is a single validated struct field. Struct collects the problem reported by each field.
func OptionalString ¶
OptionalString validates an optional string field addressed by a pointer. When the pointer is nil the field is treated as absent (no rules run).
type Problems ¶
Problems maps a json-style field name to its validation problem. nil means no problems. It is a defined type so it reads as a domain type at call sites and leaves room to grow, while still marshaling like its underlying map and being assignable to a plain map[string]string.
type Rule ¶
Rule validates a value of type T, returning an error whose message becomes the field's problem, or nil when the value is ok.
func Each ¶
Each wraps per-element rules into a single slice rule, reporting "element #i: <problem>" on the first failing element.
func In ¶
In asserts the value equals one of the allowed values. It accepts ~string values (e.g. enum value slices via In(TypeValues()...)) and is usable inside Each.