-
Notifications
You must be signed in to change notification settings - Fork 1
/
form.go
75 lines (60 loc) · 1.44 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
/*
wtforms Package
Golang的表单包
提供表单定义,验证,HTML渲染
目前还不是很完善,不久后作为一个包开源
灵感来自Python的WTForms库,http://wtforms.simplecodes.com/
*/
package wtforms
import (
"errors"
"html/template"
"net/http"
"strings"
)
type Form struct {
fields map[string]IField
}
func NewForm(fields ...IField) *Form {
form := Form{}
form.fields = make(map[string]IField)
for _, field := range fields {
form.fields[field.GetName()] = field
}
return &form
}
func (form *Form) Validate(r *http.Request) bool {
result := true
for name, field := range form.fields {
field.SetValue(strings.TrimSpace(r.FormValue(name)))
if !field.Validate() {
result = false
}
}
return result
}
func (form *Form) RenderLabel(name string, attrs ...string) template.HTML {
field := form.fields[name]
return field.RenderLabel(attrs...)
}
func (form *Form) RenderInput(name string, attrs ...string) template.HTML {
field := form.fields[name]
return field.RenderInput(attrs...)
}
func (form *Form) Value(name string) string {
return form.fields[name].GetValue()
}
func (form *Form) SetValue(name, value string) {
form.fields[name].SetValue(value)
}
func (form *Form) AddError(name, err string) {
field := form.fields[name]
field.AddError(err)
}
func (form *Form) Field(name string) (IField, error) {
field, ok := form.fields[name]
if !ok {
return nil, errors.New("not this field: " + name)
}
return field, nil
}