-
Notifications
You must be signed in to change notification settings - Fork 0
/
form.go
150 lines (113 loc) · 2.34 KB
/
form.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
package happyngine
type FormElementInterface interface {
Name() string
Validate(*Context)
SetFormValue(string)
FormValue() string
SetValue(interface{})
Value() interface{}
Error() string
Required() bool
Found() bool
}
type FormElement struct {
name string
formValue string
value interface{}
errorString string
required bool
handlers []FormValidatorHandler
found bool
}
func NewFormElement(name, errStr string) *FormElement {
return &FormElement{
name: name,
formValue: "",
value: nil,
errorString: errStr,
required: true,
}
}
func (e *FormElement) Name() string {
return e.name
}
func (e *FormElement) Validate(c *Context) {
for _, h := range e.handlers {
h(c, e)
if c.HasErrors() {
break
}
}
}
func (e *FormElement) SetFormValue(v string) {
e.formValue = v
e.found = true
}
func (e *FormElement) FormValue() string {
return e.formValue
}
func (e *FormElement) SetValue(i interface{}) {
e.value = i
}
func (e *FormElement) Value() interface{} {
return e.value
}
func (e *FormElement) Found() bool {
return e.found
}
func (e *FormElement) Error() string {
return e.errorString
}
func (e *FormElement) Required() bool {
return e.required
}
func (e *FormElement) SetRequired(r bool) *FormElement {
e.required = r
return e
}
func (e *FormElement) AddValidator(h FormValidatorHandler) *FormElement {
e.handlers = append(e.handlers, h)
return e
}
type Form struct {
Context *Context
Elements map[string]FormElementInterface
}
func NewForm(c *Context, elems ...FormElementInterface) *Form {
f := &Form{
Context: c,
}
f.Elements = make(map[string]FormElementInterface)
for _, e := range elems {
f.Elements[e.Name()] = e
}
return f
}
func (f *Form) AddElement(e FormElementInterface) *Form {
f.Elements[e.Name()] = e
return f
}
func (f *Form) Elem(name string) FormElementInterface {
return f.Elements[name]
}
func (f *Form) fillElements() bool {
for _, e := range f.Elements {
if value := f.Context.GetParam(e.Name()); len(value) > 0 {
e.SetFormValue(value)
} else if e.Required() {
f.Context.AddError(400, e.Error())
}
}
return !f.Context.HasErrors()
}
func (f *Form) IsValid() bool {
if !f.fillElements() {
return false
}
for _, e := range f.Elements {
if e.Found() {
e.Validate(f.Context)
}
}
return !f.Context.HasErrors()
}