add Collect: run every validator and join all errors
Collect is the all-errors-at-once counterpart to All. All still stops at the first failure (unchanged); Collect runs every function and returns the failures joined with errors.Join, which errors.Is still matches element by element. Kept as a separate function rather than a flag on All so All's signature and behaviour don't change. Closes #5 Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit was merged in pull request #10.
This commit is contained in:
+24
@@ -0,0 +1,24 @@
|
||||
package validate
|
||||
|
||||
import (
|
||||
"errors"
|
||||
)
|
||||
|
||||
// Collect validates a value against a sequence of validation functions,
|
||||
// like All, but runs every function instead of stopping at the first
|
||||
// failure. All failures are returned together as one joined error (see
|
||||
// errors.Join); errors.Is still matches each individual error contained in
|
||||
// it. If nothing fails, Collect returns nil.
|
||||
func Collect[T any](fs ...func(T) error) func(T) error {
|
||||
return func(value T) error {
|
||||
var errs []error
|
||||
|
||||
for _, f := range fs {
|
||||
if err := f(value); err != nil {
|
||||
errs = append(errs, err)
|
||||
}
|
||||
}
|
||||
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user