-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGinFormValidation.go
49 lines (40 loc) · 1.16 KB
/
GinFormValidation.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package GinFormValidation
import (
"gopkg.in/go-playground/validator.v9"
"reflect"
"strings"
)
type ErrorJsonSchema struct {
Errors []ErrorJsonSchemaChild `json:"errors"`
}
type ErrorJsonSchemaChild struct {
Column string `json:"column"`
Contents []string `json:"messages"`
}
func ErrorsToJson(form interface{}, err error, messageTranslationCallback func(message string) string) interface{} {
errors := err.(validator.ValidationErrors)
f := reflect.TypeOf(form)
parent := ErrorJsonSchema{}
for _, e := range errors {
field, _ := f.FieldByName(e.Field())
tags := []string{}
items := strings.Split(field.Tag.Get("bind_error"), ",")
for _, item := range items {
keyValue := strings.Split(item,"=")
if e.Tag() == strings.TrimSpace(keyValue[0]) {
var translatedValue string
if messageTranslationCallback != nil {
translatedValue = messageTranslationCallback(keyValue[1])
} else {
translatedValue = keyValue[1]
}
tags = append(tags, strings.TrimSpace(translatedValue))
}
}
child := ErrorJsonSchemaChild{}
child.Column = e.Field()
child.Contents = tags
parent.Errors = append(parent.Errors, child)
}
return parent
}