This repository has been archived by the owner on May 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
custom.go
92 lines (78 loc) · 1.75 KB
/
custom.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package main
import (
"errors"
"fmt"
"regexp"
"strconv"
"github.com/grupozap/aegir/internal/pkg/utils"
livr "github.com/k33nice/go-livr"
)
var (
defaultRegex = regexp.MustCompile(".*")
)
func neq(args ...interface{}) livr.Validation {
notAllowed := utils.FirstArg(args...)
return func(value interface{}, builders ...interface{}) (interface{}, interface{}) {
if value == nil || value == "" {
return nil, nil
}
switch value.(type) {
case float64, string, bool:
default:
return nil, errors.New("FORMAT_ERROR")
}
if fmt.Sprint(value) == fmt.Sprint(notAllowed) {
return nil, errors.New("NOT_ALLOWED_VALUE")
}
return value, nil
}
}
func not_like(args ...interface{}) livr.Validation {
var re *regexp.Regexp
var flags string
if len(args) > 0 {
if len(args) > 1 {
if v, ok := args[1].(string); ok {
if v == "i" {
flags = "(?i)"
}
}
}
if v, ok := args[0].(string); ok {
reg, err := regexp.Compile(flags + v)
if err != nil {
re = defaultRegex
} else {
re = reg
}
}
}
return func(value interface{}, builders ...interface{}) (interface{}, interface{}) {
if value == nil || value == "" {
return value, nil
}
switch v := value.(type) {
case string:
if matches := re.MatchString(v); matches {
return nil, errors.New("WRONG_FORMAT")
}
return v, nil
case float64:
if matches := re.MatchString(strconv.FormatFloat(v, 'f', -1, 64)); matches {
return nil, errors.New("WRONG_FORMAT")
}
return v, nil
default:
return nil, errors.New("FORMAT_ERROR")
}
}
}
var customRules map[string]livr.Builder
func init() {
customRules = map[string]livr.Builder{
"neq": neq,
"not_like": not_like,
}
v := livr.New(&livr.Options{})
v.RegisterDefaultRules(customRules)
}