validate

package
v0.11.1 Latest Latest
Warning

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

Go to latest
Published: Jul 26, 2026 License: MIT Imports: 2 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrInvalid = errors.New("invalid")

ErrInvalid is the sentinel error returned when validation fails.

Functions

func All

func All(rules ...Rule) error

All evaluates every rule and returns a combined error wrapping ErrInvalid if any of them fail. All rules are always evaluated regardless of earlier failures.

func Any

func Any(rules ...Rule) error

Any evaluates rules in order and returns an error wrapping ErrInvalid as soon as the first rule fails. Returns nil if all rules pass.

Types

type Rule

type Rule interface {
	// contains filtered or unexported methods
}

Rule represents a single validation rule that can be tested.

func Group

func Group(name string, rules ...Rule) Rule

Group creates a Rule that evaluates the given rules using Any (short-circuit) and, if any rule fails, prefixes the resulting error with name for context. This is useful for grouping related validations under a descriptive label (e.g., a field name) so that error messages clearly indicate which group failed.

Example usage:

validate.Group("email",
    validate.That(email != "", "is required"),
    validate.That(isValidEmail(email), "must be a valid email address"),
)

type RuleFunc

type RuleFunc func() error

RuleFunc is an adapter to allow the use of ordinary functions as Rules.

func That

func That(when bool, format string, args ...any) RuleFunc

That creates a RuleFunc from a boolean condition.

The when parameter controls whether the rule passes or fails:

  • If when is true, the rule passes (returns nil).
  • If when is false, an error is constructed from the remaining arguments.

The format parameter is a message string (or fmt-style format verb string) describing the validation failure. Any additional args are passed to fmt.Errorf as format parameters. If no args are provided, format is used directly as the error message via errors.New.

Example usage:

validate.That(age >= 18, "age must be at least 18, got %d", age)
validate.That(name != "", "name is required")

Jump to

Keyboard shortcuts

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