Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add a tag validation method #1230

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
19 changes: 19 additions & 0 deletions validator_instance.go
Expand Up @@ -707,3 +707,22 @@ func (v *Validate) VarWithValueCtx(ctx context.Context, field interface{}, other
v.pool.Put(vd)
return
}

// ValidateTag validates a tag. It's main purpose is to be used when validating values directly via the Var, VarCtx,
// VarWithValue and VarWithValueCtx methods to know beforehand if the tag is known by the library instead of managing
// a panic error.
//
// Parameters:
// tag (string): The tag to be validated.
//
// Returns:
// error: An error signaling the given tag is invalid.
func (v *Validate) ValidateTag(tag string) (err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("error parsing tag: %v", r)
}
}()
v.parseFieldTagsRecursive(tag, "", "", false)
return err
}
8 changes: 8 additions & 0 deletions validator_test.go
Expand Up @@ -13692,3 +13692,11 @@ func TestOmitNilAndRequired(t *testing.T) {
AssertError(t, err2, "OmitNil.Inner.Str", "OmitNil.Inner.Str", "Str", "Str", "required")
})
}

func TestValidate_ValidateTag(t *testing.T) {
validate := New()
err := validate.ValidateTag("nonexsiting,nonexisting2")
NotEqual(t, err, nil)
err = validate.ValidateTag("required,email")
Equal(t, err, nil)
}