From b0c733737d69470434d9f2358e6e83f6de60669a Mon Sep 17 00:00:00 2001 From: Dean Karn Date: Sat, 4 Nov 2023 08:36:25 -0700 Subject: [PATCH] update fieldMatchesRegexByStringerValOrString for backward compatibility --- util.go | 12 +++++++++--- validator_test.go | 13 +++++++++++++ 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/util.go b/util.go index c8b901db..16851593 100644 --- a/util.go +++ b/util.go @@ -298,8 +298,14 @@ func panicIf(err error) { // Checks if field value matches regex. If fl.Field can be cast to Stringer, it uses the Stringer interfaces // String() return value. Otherwise, it uses fl.Field's String() value. func fieldMatchesRegexByStringerValOrString(regex *regexp.Regexp, fl FieldLevel) bool { - if stringer, ok := fl.Field().Interface().(fmt.Stringer); ok { - return regex.MatchString(stringer.String()) + switch fl.Field().Kind() { + case reflect.String: + return regex.MatchString(fl.Field().String()) + default: + if stringer, ok := fl.Field().Interface().(fmt.Stringer); ok { + return regex.MatchString(stringer.String()) + } else { + return regex.MatchString(fl.Field().String()) + } } - return regex.MatchString(fl.Field().String()) } diff --git a/validator_test.go b/validator_test.go index b5949ac7..3ea90e29 100644 --- a/validator_test.go +++ b/validator_test.go @@ -4113,7 +4113,14 @@ func (u uuidTestType) String() string { return u.val } +type uuidAlias string + +func (u uuidAlias) String() string { + return "This is a UUID " + string(u) +} + var _ fmt.Stringer = uuidTestType{} +var _ fmt.Stringer = uuidAlias("") func TestUUIDValidation(t *testing.T) { tests := []struct { @@ -4170,6 +4177,12 @@ func TestUUIDValidation(t *testing.T) { if err := validate.Struct(structWithInvalidUUID); err == nil { t.Fatal("UUID failed Error expected but received nil") } + + // Test on Alias type with Stringer interface. + alias := uuidAlias("a987fbc9-4bed-3078-cf07-9141ba07c9f3") + if err := validate.Var(alias, "uuid"); err != nil { + t.Fatalf("UUID failed Error: %s", err) + } } func TestUUID5RFC4122Validation(t *testing.T) {