-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
8438ef0
commit 01a89ce
Showing
3 changed files
with
27 additions
and
45 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,44 +1,23 @@ | ||
package validation | ||
|
||
import "github.com/pkg/errors" | ||
|
||
// Rule is the interface for all validation rules. | ||
type Rule[T any] interface { | ||
Validate(v T) error | ||
} | ||
|
||
// SingleRule represents a single validation Rule. | ||
// The Message conveys the reason for the rules' failure and IsValid | ||
// is the function which verifies if the rule passes or not. | ||
type SingleRule[T any] struct { | ||
Message string | ||
IsValid func(v T) bool | ||
} | ||
type SingleRule[T any] func(v T) error | ||
|
||
func (r SingleRule[T]) Validate(v T) error { | ||
if r.IsValid(v) { | ||
return nil | ||
} | ||
return errors.New(r.Message) | ||
} | ||
func (r SingleRule[T]) Validate(v T) error { return r(v) } | ||
|
||
// MultiRule allows defining Rule which aggregates multiple sub-rules. | ||
type MultiRule[T any] struct { | ||
Rules []Rule[T] | ||
} | ||
type MultiRule[T any] []Rule[T] | ||
|
||
func (r MultiRule[T]) Validate(v T) error { | ||
var mErr multiRuleError | ||
for i := range r.Rules { | ||
if err := r.Rules[i].Validate(v); err != nil { | ||
for i := range r { | ||
if err := r[i].Validate(v); err != nil { | ||
mErr = append(mErr, err) | ||
} | ||
} | ||
return mErr | ||
} | ||
|
||
// SingleRuleFunc is a function variant of SingleRule. | ||
// Instead of defining message and validation check separately it can be used to | ||
type SingleRuleFunc[T any] func(v T) error | ||
|
||
func (r SingleRuleFunc[T]) Validate(v T) error { return r(v) } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters