Skip to content

Commit

Permalink
Add yav.NamedValidateFunc and vpointer.Required
Browse files Browse the repository at this point in the history
  • Loading branch information
SladeThe committed Oct 9, 2023
1 parent 4664804 commit e600238
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
15 changes: 15 additions & 0 deletions vpointer/required.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,20 @@
package vpointer

import (
"github.com/SladeThe/yav"
)

func OmitEmpty[T any](_ string, value *T) (stop bool, err error) {
return value == nil, nil
}

func Required[T any](name string, value *T) (stop bool, err error) {
if value == nil {
return true, yav.Error{
CheckName: yav.CheckNameRequired,
ValueName: name,
}
}

return false, nil
}
50 changes: 50 additions & 0 deletions yav.go
Original file line number Diff line number Diff line change
Expand Up @@ -161,3 +161,53 @@ func NestedValidate[T Validatable](name string, value T) (stop bool, err error)
err = value.Validate()
return err != nil, Nested(name, err)
}

// NamedCheck processes errors of either Error or Errors type,
// clearing Error.Parameter and replacing Error.CheckName with the given name.
// Unsupported and nil errors are returned as is.
func NamedCheck(checkName string, err error) error {
if err == nil {
return nil
}

switch typedErr := err.(type) {
case Error:
return namedCheckYAV(checkName, typedErr)
case Errors:
for i, yavErr := range typedErr.Validation {
typedErr.Validation[i] = namedCheckYAV(checkName, yavErr)
}

return typedErr
default:
return err
}
}

func namedCheckYAV(checkName string, yavErr Error) Error {
yavErr.CheckName = checkName
yavErr.Parameter = ""
return yavErr
}

// NamedValidateFunc combines the given validation funcs into a new named one.
// Those functions are invoked similarly to Chain, then NamedCheck is applied to the result.
func NamedValidateFunc[T any](checkName string, validateFuncs ...ValidateFunc[T]) ValidateFunc[T] {
if len(validateFuncs) == 0 {
return Next[T]
}

return func(name string, value T) (stop bool, err error) {
var yavErrs Errors

for _, validateFunc := range validateFuncs {
stop, err = validateFunc(name, value)
yavErrs.Append(err)
if stop {
break
}
}

return stop, NamedCheck(checkName, yavErrs.AsError())
}
}

0 comments on commit e600238

Please sign in to comment.