Skip to content

Commit

Permalink
update fieldMatchesRegexByStringerValOrString for backward compatibility
Browse files Browse the repository at this point in the history
  • Loading branch information
deankarn committed Nov 4, 2023
1 parent 4c1bd61 commit b0c7337
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
12 changes: 9 additions & 3 deletions util.go
Original file line number Diff line number Diff line change
Expand Up @@ -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())
}
13 changes: 13 additions & 0 deletions validator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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) {
Expand Down

0 comments on commit b0c7337

Please sign in to comment.