Documentation
¶
Overview ¶
Package validator is a simple library for validating conditions. Conditions are defined with rules; If the rule fails, an error is returned.
err := validator.Validate(
validator.Rule(false, "must be false"),
)
if errors.Is(err, validator.ErrInvalid) {
// handle validation error
}
The validator package also provides a function Any() that returns the first error encountered, or nil if all rules pass.
err := validator.Validate( validator.Any( validator.Rule(false, "must be false"), validator.Rule(true, "must be true"), ), ) // returns "validation error: must be false"
The validator package also provides a function All() that evaluates all rules in the list:
err := validator.Validate(
validator.All(
validator.Rule(true, "must be true"),
validator.Rule(false, "must be false"),
),
) // returns "validation error: must be false"
if errors.Is(err, validator.ErrInvalid) {
// handle validation error
}
Index ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrInvalid is the sentinel error that is wrapped by any error returned // by Validate(). // // err := validator.Validate( // validator.Rule(true, "must be true"), // validator.Rule(false, "must be false"), // ) // // if errors.Is(err, validator.ErrInvalid) { // // handle validation error // } ErrInvalid = errors.New("validation error") )
Functions ¶
func Validate ¶
func Validate(rule ValidationRule) error
Validate evaluates the given validation rule. If the rule fails an validation error is returned.
Types ¶
type ValidationRule ¶
type ValidationRule func() error
ValidationRule functions return an error if the validation fails.
func All ¶
func All(rules ...ValidationRule) ValidationRule
All evaluates all rules in the list, and returns the first error encountered, or nil if all rules pass.
func Any ¶
func Any(rules ...ValidationRule) ValidationRule
Any evaluates all rules in the list and returns the first error encountered, or nil if all rules pass.
func If ¶
func If(test bool, rule ValidationRule) ValidationRule
If returns a rule that is only executed if the given condition is true.