forked from alash3al/sqler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
validate.go
48 lines (44 loc) · 1.28 KB
/
validate.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
// Copyright 2018 The SQLer Authors. All rights reserved.
// Use of this source code is governed by a Apache 2.0
// license that can be found in the LICENSE file.
package main
import (
"fmt"
"strings"
"github.com/asaskevich/govalidator"
)
// Validate - validates the specified data against the specified validators
func Validate(data map[string]interface{}, validators map[string][]string) map[string][]string {
invalid, result := 0, map[string][]string{}
for k, rules := range validators {
result[k] = []string{}
value, exists := data[k]
valuestr := strings.TrimSpace(fmt.Sprintf("%v", value))
for _, r := range rules {
if r == "required" && !exists || valuestr == "" {
invalid++
result[k] = append(result[k], "required")
} else if ruler, ok := govalidator.TagMap[r]; ok && !ruler(valuestr) {
invalid++
result[k] = append(result[k], r)
} else {
parts := strings.SplitN(r, ":", 2)
if len(parts) < 2 {
parts = append(parts, "")
}
r, args := parts[0], parts[1]
args = strings.TrimSpace(args)
if ruler, ok := govalidator.ParamTagMap[r]; ok {
if !ruler(valuestr, strings.Split(args, ",")...) {
invalid++
result[k] = append(result[k], r)
}
}
}
}
if len(result[k]) < 1 {
delete(result, k)
}
}
return result
}