Skip to content

Commit cbdba6f

Browse files
committed
feat: Add a tag validation method
1 parent b328f72 commit cbdba6f

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

validator_instance.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -707,3 +707,22 @@ func (v *Validate) VarWithValueCtx(ctx context.Context, field interface{}, other
707707
v.pool.Put(vd)
708708
return
709709
}
710+
711+
// ValidateTag validates a tag. It's main purpose is to be used when validating values directly via the Var, VarCtx,
712+
// VarWithValue and VarWithValueCtx methods to know beforehand if the tag is known by the library instead of managing
713+
// a panic error.
714+
//
715+
// Parameters:
716+
// tag (string): The tag to be validated.
717+
//
718+
// Returns:
719+
// error: An error signaling the given tag is invalid.
720+
func (v *Validate) ValidateTag(tag string) (err error) {
721+
defer func() {
722+
if r := recover(); r != nil {
723+
err = fmt.Errorf("error parsing tag: %v", r)
724+
}
725+
}()
726+
v.parseFieldTagsRecursive(tag, "", "", false)
727+
return err
728+
}

validator_test.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13692,3 +13692,11 @@ func TestOmitNilAndRequired(t *testing.T) {
1369213692
AssertError(t, err2, "OmitNil.Inner.Str", "OmitNil.Inner.Str", "Str", "Str", "required")
1369313693
})
1369413694
}
13695+
13696+
func TestValidate_ValidateTag(t *testing.T) {
13697+
validate := New()
13698+
err := validate.ValidateTag("nonexsiting,nonexisting2")
13699+
NotEqual(t, err, nil)
13700+
err = validate.ValidateTag("required,email")
13701+
Equal(t, err, nil)
13702+
}

0 commit comments

Comments
 (0)