add field type for validation error

This commit is contained in:
nochill 2023-09-19 21:49:05 +07:00
parent 9a4f8e15b4
commit a866730e37

View File

@ -13,11 +13,17 @@ type APIValidationError struct {
Msg string `json:"msg"`
}
func validationErrorMsg(field string, param string, tag string) string {
func validationErrorMsg(field string, param string, tag string, typeName string) string {
switch tag {
case "min":
if typeName == "int16" || typeName == "int64" {
return fmt.Sprintf("%s(number) value min %s", field, param)
}
return fmt.Sprintf("%s character min %s character", field, param)
case "max":
if typeName == "int16" || typeName == "int64" {
return fmt.Sprintf("%s(number) value max is %s", field, param)
}
return fmt.Sprintf("%s character max %s character", field, param)
case "required":
return fmt.Sprintf("%s is %s", field, tag)
@ -32,7 +38,7 @@ func ValidationErrorResponse(err error) gin.H {
if errors.As(err, &ves) {
out := make([]APIValidationError, len(ves))
for i, ve := range ves {
out[i] = APIValidationError{ve.Field(), validationErrorMsg(ve.Field(), ve.Param(), ve.ActualTag())}
out[i] = APIValidationError{ve.Field(), validationErrorMsg(ve.Field(), ve.Param(), ve.ActualTag(), ve.Type().Name())}
}
temp = out
}