Skip to content

Commit

Permalink
Fixed country_code validation to properly handle strings (go-playgrou…
Browse files Browse the repository at this point in the history
  • Loading branch information
uberswe committed Jan 2, 2022
1 parent ce34f36 commit 19f8e61
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 3 deletions.
6 changes: 6 additions & 0 deletions baked_in.go
Original file line number Diff line number Diff line change
Expand Up @@ -2351,6 +2351,12 @@ func isIso3166AlphaNumeric(fl FieldLevel) bool {

var code int
switch field.Kind() {
case reflect.String:
i, err := strconv.Atoi(field.String())
if err != nil {
return false
}
code = i % 1000
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
code = int(field.Int() % 1000)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
Expand Down
42 changes: 39 additions & 3 deletions validator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11053,12 +11053,15 @@ func TestIsIso3166Alpha3Validation(t *testing.T) {

func TestIsIso3166AlphaNumericValidation(t *testing.T) {
tests := []struct {
value int
value interface{}
expected bool
}{
{248, true},
{"248", true},
{0, false},
{1, false},
{"1", false},
{"invalid_int", false},
}

validate := New()
Expand All @@ -11079,8 +11082,41 @@ func TestIsIso3166AlphaNumericValidation(t *testing.T) {
}

PanicMatches(t, func() {
_ = validate.Var("1", "iso3166_1_alpha_numeric")
}, "Bad field type string")
_ = validate.Var([]string{"1"}, "iso3166_1_alpha_numeric")
}, "Bad field type []string")
}

func TestCountryCodeValidation(t *testing.T) {
tests := []struct {
value interface{}
expected bool
}{
{248, true},
{0, false},
{1, false},
{"POL", true},
{"NO", true},
{"248", true},
{"1", false},
{"0", false},
}

validate := New()

for i, test := range tests {

errs := validate.Var(test.value, "country_code")

if test.expected {
if !IsEqual(errs, nil) {
t.Fatalf("Index: %d country_code failed Error: %s", i, errs)
}
} else {
if IsEqual(errs, nil) {
t.Fatalf("Index: %d country_code failed Error: %s", i, errs)
}
}
}
}

func TestIsIso4217Validation(t *testing.T) {
Expand Down

0 comments on commit 19f8e61

Please sign in to comment.