-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathform.go
83 lines (72 loc) · 1.82 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
package ussd
import "github.com/samora/ussd-go/validator"
// Form is a USSD form.
type Form struct {
Title, ValidationMessage string
Route route
ProcessingPosition int
Data FormData
Inputs []input
}
// NewForm creates a new form.
func NewForm(title string) *Form {
return &Form{
Title: StrTrim(title),
Data: make(FormData),
Inputs: make([]input, 0),
}
}
// Input adds an input to USSD form.
func (f *Form) Input(name, displayName string,
options ...option) *Form {
input := newInput(StrTrim(name), StrTrim(displayName))
for _, option := range options {
input.Options = append(input.Options, option)
}
f.Inputs = append(f.Inputs, input)
return f
}
// Validate input. See validator.Map for available validators.
func (f *Form) Validate(validatorKey string, args ...string) *Form {
validatorKey = StrTrim(StrLower(validatorKey))
if _, ok := validator.Map[validatorKey]; !ok {
panic(&validatorDoesNotExistError{validatorKey})
}
i := len(f.Inputs) - 1
input := f.Inputs[i]
input.Validators = append(input.Validators, validatorData{
Key: validatorKey,
Args: args,
})
f.Inputs[i] = input
return f
}
// Option creates a USSD input option.
func (f Form) Option(value, displayValue string) option {
return option{
Value: StrTrim(value), DisplayValue: StrTrim(displayValue),
}
}
type input struct {
Name, DisplayName string
Options []option
Validators []validatorData
}
type option struct {
Value, DisplayValue string
}
type validatorData struct {
Key string
Args []string
}
func newInput(name, displayName string) input {
return input{
Name: name,
DisplayName: displayName,
Options: make([]option, 0),
Validators: make([]validatorData, 0),
}
}
func (i input) hasOptions() bool {
return len(i.Options) > 0
}