-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Description
- I have looked at the documentation here first?
- I have looked at the examples provided that may showcase my question here?
Package version eg. v9, v10: v10
Issue, Question or Enhancement:
In #615 the country_code
alias is introduced which calls 3 validators iso3166_1_alpha2|iso3166_1_alpha3|iso3166_1_alpha_numeric
.
If you use the country_code
to validate a string which has an invalid value you will receive a panic with the message Bad field type string
. This is caused by the iso3166_1_alpha_numeric
validation here
Line 2359 in ce34f36
panic(fmt.Sprintf("Bad field type %T", field.Interface())) |
Code sample, to showcase or reproduce:
This is a test I wrote to confirm the issue, you will receive a panic on "1"
.
func TestCountryCodeValidation(t *testing.T) {
tests := []struct {
value interface{}
expected bool
}{
{248, true},
{0, false},
{1, false},
{"NO", 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)
}
}
}
}
Expected behaviour
I would expect that the alias should not panic here but instead return false.
Fix
I was planning to make a PR for this issue but the fix may require some big changes and I thought it may be good to discuss them before making any kind of changes.
A simple solution would be to catch any panic for an alias, this makes sense for country_code
which can have multiple valid types.
An easier solution would be to just remove the panic in the iso3166_1_alpha_numeric
function but then it would differ from the rest of the package. That raises another question of whether the package should be throwing panics in the first place?
I am not sure what the best way to solve this would be and would look for input from maintainers or perhaps @krhubert who added this functionality.