Skip to content

Commit 19f8e61

Browse files
authored
Fixed country_code validation to properly handle strings (#873)
1 parent ce34f36 commit 19f8e61

File tree

2 files changed

+45
-3
lines changed

2 files changed

+45
-3
lines changed

baked_in.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2351,6 +2351,12 @@ func isIso3166AlphaNumeric(fl FieldLevel) bool {
23512351

23522352
var code int
23532353
switch field.Kind() {
2354+
case reflect.String:
2355+
i, err := strconv.Atoi(field.String())
2356+
if err != nil {
2357+
return false
2358+
}
2359+
code = i % 1000
23542360
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
23552361
code = int(field.Int() % 1000)
23562362
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:

validator_test.go

Lines changed: 39 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11053,12 +11053,15 @@ func TestIsIso3166Alpha3Validation(t *testing.T) {
1105311053

1105411054
func TestIsIso3166AlphaNumericValidation(t *testing.T) {
1105511055
tests := []struct {
11056-
value int
11056+
value interface{}
1105711057
expected bool
1105811058
}{
1105911059
{248, true},
11060+
{"248", true},
1106011061
{0, false},
1106111062
{1, false},
11063+
{"1", false},
11064+
{"invalid_int", false},
1106211065
}
1106311066

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

1108111084
PanicMatches(t, func() {
11082-
_ = validate.Var("1", "iso3166_1_alpha_numeric")
11083-
}, "Bad field type string")
11085+
_ = validate.Var([]string{"1"}, "iso3166_1_alpha_numeric")
11086+
}, "Bad field type []string")
11087+
}
11088+
11089+
func TestCountryCodeValidation(t *testing.T) {
11090+
tests := []struct {
11091+
value interface{}
11092+
expected bool
11093+
}{
11094+
{248, true},
11095+
{0, false},
11096+
{1, false},
11097+
{"POL", true},
11098+
{"NO", true},
11099+
{"248", true},
11100+
{"1", false},
11101+
{"0", false},
11102+
}
11103+
11104+
validate := New()
11105+
11106+
for i, test := range tests {
11107+
11108+
errs := validate.Var(test.value, "country_code")
11109+
11110+
if test.expected {
11111+
if !IsEqual(errs, nil) {
11112+
t.Fatalf("Index: %d country_code failed Error: %s", i, errs)
11113+
}
11114+
} else {
11115+
if IsEqual(errs, nil) {
11116+
t.Fatalf("Index: %d country_code failed Error: %s", i, errs)
11117+
}
11118+
}
11119+
}
1108411120
}
1108511121

1108611122
func TestIsIso4217Validation(t *testing.T) {

0 commit comments

Comments
 (0)