Join GitHub today
GitHub is home to over 50 million developers working together to host and review code, manage projects, and build software together.
Sign upValidation issue #2334
Validation issue #2334
Comments
|
@dimuska139 The panic comes from type assertion line: errs := err.(validator.ValidationErrors)
You probably need to do something like: errs, ok := err.(validator.ValidationErrors)
if !ok {
c.String(400, "Handle differently")
return
}or this, which is even better handling IMO: switch err.(type) {
case validator.ValidationErrors:
respErrors := make(map[string]interface{})
for _, v := range err.(validator.ValidationErrors) {
field, _ := reflect.TypeOf(&pag).Elem().FieldByName(v.Field())
fieldName, _ := field.Tag.Lookup("form")
respErrors[fieldName] = v.Tag()
}
c.JSON(http.StatusBadRequest, gin.H{"errors": respErrors})
case *strconv.NumError:
c.String(400, "Handle differently")
} |
|
@canercidam yes, you are right. But this method doesn't allow to know which field has error. Because of strconv.NumError has no information about validation. |
|
@dimuska139 True. I understand the problem better now. The number conversion error comes from It should also be possible to use a different query binding in |
|
@canercidam I've fixed it by using thedevsaddam/govalidator before ShouldBindQuery but I think that it's not a good solution. rules := govalidator.MapData{
"page": []string{"required", "numeric", "numeric_between:1,"},
"page_size": []string{"required", "numeric", "numeric_between:1,100"},
}
type Paginator struct {
Page int `form:"page"`
PageSize int `form:"page_size"`
}
var pag Paginator
opts := govalidator.Options{
Request: c.Request,
Data: &pag,
Rules: rules,
}
v := govalidator.New(opts)
errs := v.Validate()
if len(errs) != 0 {
c.JSON(http.StatusOK, gin.H{
"errors": errs,
"meta": nil,
"data": nil,
})
return
}
c.ShouldBindQuery(&pag) |


Description
There is no way to handle validation error If struct field has type "int" and user sends string value.
How to reproduce
Expectations
For example:
/articles?page=1is correct but/articles?page=stringisherethrows panic. How to resolve this situation and return correct error message{"errors":"page":"Number expected"}?Environment