diff --git a/slices.go b/slices.go index ddb90d3..4c19c32 100644 --- a/slices.go +++ b/slices.go @@ -79,7 +79,7 @@ func (v *sliceProcessor) process(val any, dest any, path p.PathBuilder, ctx p.Pa return } else { // REQUIRED & ZERO VALUE - ctx.NewError(path, Errors.Required(val, destType)) + ctx.NewError(path, Errors.FromTest(val, destType, v.required, ctx)) return } } else { diff --git a/string.go b/string.go index 443df22..43a6254 100644 --- a/string.go +++ b/string.go @@ -1,6 +1,7 @@ package zog import ( + "net/url" "regexp" "strings" @@ -10,7 +11,6 @@ import ( var ( emailRegex = regexp.MustCompile("^[a-zA-Z0-9.!#$%&'*+\\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$") - urlRegex = regexp.MustCompile(`^(http(s)?://)?([\da-z\.-]+)\.([a-z\.]{2,6})([/\w \.-]*)*/?$`) ) type stringProcessor struct { @@ -166,12 +166,12 @@ func (v *stringProcessor) URL(options ...TestOption) *stringProcessor { t := p.Test{ ErrCode: p.ErrCodeURL, ValidateFunc: func(v any, ctx p.ParseCtx) bool { - u, ok := v.(string) + s, ok := v.(string) if !ok { return false } - isOk := urlRegex.MatchString(u) - return isOk + u, err := url.Parse(s) + return err == nil && u.Scheme != "" && u.Host != "" }, } for _, opt := range options { diff --git a/string_test.go b/string_test.go index 89eb92b..c279f37 100644 --- a/string_test.go +++ b/string_test.go @@ -94,11 +94,12 @@ func TestStringLength(t *testing.T) { } func TestStringRequired(t *testing.T) { - field := String().Required() + field := String().Required(Message("a")) var dest string errs := field.Parse("", &dest) assert.NotEmpty(t, errs) + assert.Equal(t, errs[0].Message(), "a") errs = field.Parse("foo", &dest) assert.Empty(t, errs) diff --git a/struct.go b/struct.go index e601ee6..3258c6f 100644 --- a/struct.go +++ b/struct.go @@ -116,7 +116,7 @@ func (v *structProcessor) process(data any, dest any, path p.PathBuilder, ctx p. if v.required == nil { return } else { - ctx.NewError(path, Errors.Required(data, destType)) + ctx.NewError(path, Errors.FromTest(data, destType, v.required, ctx)) return } } diff --git a/utils.go b/utils.go index 46ea26f..d1cea44 100644 --- a/utils.go +++ b/utils.go @@ -60,10 +60,6 @@ func (e *errHelpers) WrapUnknown(o any, destType p.ZogType, err error) p.ZogErro return zerr } -func (e *errHelpers) Required(o any, destType p.ZogType) p.ZogError { - return e.New(p.ErrCodeRequired, o, destType, nil, "", nil) -} - func (e *errHelpers) New(code p.ZogErrCode, o any, destType p.ZogType, params map[string]any, msg string, err error) p.ZogError { return &p.ZogErr{ C: code, @@ -178,7 +174,7 @@ func primitiveProcessor[T p.ZogPrimitive](val any, dest any, path p.PathBuilder, *destPtr = *catch hasCatched = true } else { - ctx.NewError(path, Errors.Required(val, destType)) + ctx.NewError(path, Errors.FromTest(val, destType, required, ctx)) return } }