Skip to content

Commit b0c7337

Browse files
author
Dean Karn
committed
update fieldMatchesRegexByStringerValOrString for backward compatibility
1 parent 4c1bd61 commit b0c7337

File tree

2 files changed

+22
-3
lines changed

2 files changed

+22
-3
lines changed

util.go

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -298,8 +298,14 @@ func panicIf(err error) {
298298
// Checks if field value matches regex. If fl.Field can be cast to Stringer, it uses the Stringer interfaces
299299
// String() return value. Otherwise, it uses fl.Field's String() value.
300300
func fieldMatchesRegexByStringerValOrString(regex *regexp.Regexp, fl FieldLevel) bool {
301-
if stringer, ok := fl.Field().Interface().(fmt.Stringer); ok {
302-
return regex.MatchString(stringer.String())
301+
switch fl.Field().Kind() {
302+
case reflect.String:
303+
return regex.MatchString(fl.Field().String())
304+
default:
305+
if stringer, ok := fl.Field().Interface().(fmt.Stringer); ok {
306+
return regex.MatchString(stringer.String())
307+
} else {
308+
return regex.MatchString(fl.Field().String())
309+
}
303310
}
304-
return regex.MatchString(fl.Field().String())
305311
}

validator_test.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4113,7 +4113,14 @@ func (u uuidTestType) String() string {
41134113
return u.val
41144114
}
41154115

4116+
type uuidAlias string
4117+
4118+
func (u uuidAlias) String() string {
4119+
return "This is a UUID " + string(u)
4120+
}
4121+
41164122
var _ fmt.Stringer = uuidTestType{}
4123+
var _ fmt.Stringer = uuidAlias("")
41174124

41184125
func TestUUIDValidation(t *testing.T) {
41194126
tests := []struct {
@@ -4170,6 +4177,12 @@ func TestUUIDValidation(t *testing.T) {
41704177
if err := validate.Struct(structWithInvalidUUID); err == nil {
41714178
t.Fatal("UUID failed Error expected but received nil")
41724179
}
4180+
4181+
// Test on Alias type with Stringer interface.
4182+
alias := uuidAlias("a987fbc9-4bed-3078-cf07-9141ba07c9f3")
4183+
if err := validate.Var(alias, "uuid"); err != nil {
4184+
t.Fatalf("UUID failed Error: %s", err)
4185+
}
41734186
}
41744187

41754188
func TestUUID5RFC4122Validation(t *testing.T) {

0 commit comments

Comments
 (0)