This repository has been archived by the owner on Feb 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathvalidator.go
90 lines (77 loc) · 1.6 KB
/
validator.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
package component
import (
"fmt"
"github.com/jroimartin/gocui"
)
// Validate validate struct
type Validate struct {
ErrMsg string
Do func(value string) bool
}
// Validator validate struct
type Validator struct {
*gocui.Gui
name string
errMsg string
isValid bool
validates []Validate
*Position
}
// NewValidator new validator
func NewValidator(gui *gocui.Gui, name string, x, y, w, h int) *Validator {
return &Validator{
Gui: gui,
name: name,
isValid: true,
Position: &Position{
X: x,
Y: y,
W: w,
H: h,
},
}
}
// AddValidate add validate
func (v *Validator) AddValidate(errMsg string, validate func(value string) bool) {
v.validates = append(v.validates, Validate{
ErrMsg: errMsg,
Do: validate,
})
if v.X+len(errMsg) > v.W {
v.W += len(errMsg)
}
}
// DispValidateMsg display validate error message
func (v *Validator) DispValidateMsg() {
if vi, err := v.SetView(v.name, v.X, v.Y, v.W, v.H); err != nil {
if err != gocui.ErrUnknownView {
panic(err)
}
vi.Frame = false
vi.BgColor = gocui.ColorDefault
vi.FgColor = gocui.ColorRed
fmt.Fprint(vi, v.errMsg)
}
}
// CloseValidateMsg close validate error message
func (v *Validator) CloseValidateMsg() {
v.DeleteView(v.name)
}
// IsValid if valid return true
func (v *Validator) IsValid() bool {
return v.isValid
}
// Validate validate value
func (v *Validator) Validate(value string) {
for _, validate := range v.validates {
if !validate.Do(value) {
v.errMsg = validate.ErrMsg
v.isValid = false
v.DispValidateMsg()
break
} else {
v.isValid = true
v.CloseValidateMsg()
}
}
}