-
Notifications
You must be signed in to change notification settings - Fork 0
/
demo_check.go
58 lines (47 loc) · 1.1 KB
/
demo_check.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
package main
import (
"fmt"
"github.com/pengux/check"
"strings"
)
type User struct {
Username string
}
type CustomStringContainValidator struct {
Constraint string
}
func (validator CustomStringContainValidator) Validate(v interface{}) check.Error {
if !strings.Contains(v.(string), validator.Constraint) {
return check.NewValidationError("customStringContainValidator", v, validator.Constraint)
}
return nil
}
func main() {
u := &User{
Username: "invalid*",
}
s := check.Struct{
"Username": check.Composite{
check.NonEmpty{},
check.Regex{`^[a-zA-Z0-9]+$`},
check.MinChar{10},
},
}
e := s.Validate(u)
if e.HasErrors() {
err, ok := e.GetErrorsByKey("Username")
if !ok {
panic("key 'Username' does not exists")
}
fmt.Println(err)
}
// custom validator
username := "invalid*"
validator := CustomStringContainValidator{"admin"}
e2 := validator.Validate(username)
fmt.Println(check.ErrorMessages[e2.Error()])
// custom error messages
check.ErrorMessages["minChar"] = "the string must be minimum %v characters long"
errMessages := e.ToMessages()
fmt.Println(errMessages)
}