dotenv, parsing fix email, moved dump tracnsport to new file gz, removed unwanted var jwt, added in HS256 sign/parse
ptr, ref and deref funcs response, use fmt.Fprint(f) validate, few new funcs
This commit is contained in:
@@ -6,6 +6,8 @@
|
||||
package validate
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strings"
|
||||
|
||||
@@ -24,8 +26,51 @@ func init() {
|
||||
}
|
||||
return name
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
func Struct(s any) error {
|
||||
return validate.Struct(s)
|
||||
// RegisterAlias for single/multuple tags
|
||||
func RegisterAlias(alias, tags string) {
|
||||
validate.RegisterAlias(alias, tags)
|
||||
}
|
||||
|
||||
func RegisterValidation(tagName string, fn validator.Func, callValidationEvenIfNull ...bool) {
|
||||
validate.RegisterValidation(tagName, fn, callValidationEvenIfNull...)
|
||||
}
|
||||
|
||||
// Struct validator
|
||||
func Struct(s any) error {
|
||||
err := validate.Struct(s)
|
||||
if IsInvalidValidationError(err) {
|
||||
return err
|
||||
}
|
||||
|
||||
var valErrs validator.ValidationErrors
|
||||
if !errors.As(err, &valErrs) {
|
||||
return err
|
||||
}
|
||||
|
||||
var sb strings.Builder
|
||||
for _, err := range valErrs {
|
||||
switch err.Tag() {
|
||||
case "required":
|
||||
sb.WriteString(fmt.Sprintf("%s: is required.\n", err.Field()))
|
||||
case "email":
|
||||
sb.WriteString(fmt.Sprintf("%s: is invalid.\n", err.Field()))
|
||||
default:
|
||||
sb.WriteString(fmt.Sprintf("%s: %q validation failed.\n", err.Field(), err.Tag()))
|
||||
}
|
||||
}
|
||||
|
||||
return errors.New(sb.String())
|
||||
}
|
||||
|
||||
// Map validator
|
||||
func Map(data map[string]any, rules map[string]any) map[string]any {
|
||||
return validate.ValidateMap(data, rules)
|
||||
}
|
||||
|
||||
func IsInvalidValidationError(err error) bool {
|
||||
var v *validator.InvalidValidationError
|
||||
return errors.As(err, &v)
|
||||
}
|
||||
|
||||
30
validate/validate_test.go
Normal file
30
validate/validate_test.go
Normal file
@@ -0,0 +1,30 @@
|
||||
package validate
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestStruct(t *testing.T) {
|
||||
type person struct {
|
||||
FirstName string `validate:"required,max=10"`
|
||||
LastName string `validate:"required"`
|
||||
Email string `validate:"email"`
|
||||
}
|
||||
|
||||
var p *person
|
||||
t.Log("check for nil value")
|
||||
if err := Struct(p); err == nil {
|
||||
t.Fatal("nil value must report and error")
|
||||
} else {
|
||||
t.Log(err.Error())
|
||||
}
|
||||
|
||||
p = new(person)
|
||||
t.Log("validation checks")
|
||||
if err := Struct(p); err == nil {
|
||||
t.Error(err)
|
||||
} else {
|
||||
t.Log(err)
|
||||
}
|
||||
|
||||
// Structure error string
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user