-
Notifications
You must be signed in to change notification settings - Fork 6
/
textbox_float.go
114 lines (96 loc) · 2.38 KB
/
textbox_float.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
package control
import (
"fmt"
"github.com/goradd/goradd/pkg/page"
"strconv"
)
// FloatTextbox is a text control that ensures a valid floating point number is entered in the field.
type FloatTextbox struct {
Textbox
}
func NewFloatTextbox(parent page.ControlI, id string) *FloatTextbox {
t := &FloatTextbox{}
t.Init(t, parent, id)
return t
}
func (i *FloatTextbox) Init(self TextboxI, parent page.ControlI, id string) {
i.Textbox.Init(self, parent, id)
i.ValidateWith(FloatValidator{})
}
func (i *FloatTextbox) SetMinValue(minValue float64, invalidMessage string) {
i.ValidateWith(MinFloatValidator{minValue, invalidMessage})
}
func (i *FloatTextbox) SetMaxValue(maxValue float64, invalidMessage string) {
i.ValidateWith(MaxFloatValidator{maxValue, invalidMessage})
}
func (i *FloatTextbox) Value() interface{} {
return i.Float64()
}
func (i *FloatTextbox) Float64() float64 {
t := i.Textbox.Text()
v, _ := strconv.ParseFloat(t, 64)
return v
}
func (i *FloatTextbox) Float32() float32 {
t := i.Textbox.Text()
v, _ := strconv.ParseFloat(t, 32)
return float32(v)
}
func (i *FloatTextbox) SetFloat64(v float64) *FloatTextbox {
i.Textbox.SetValue(v)
return i
}
func (i *FloatTextbox) SetFloat32(v float32) *FloatTextbox {
i.Textbox.SetValue(v)
return i
}
type FloatValidator struct {
Message string
}
func (v FloatValidator) Validate(c page.ControlI, s string) (msg string) {
if s == "" {
return "" // empty textbox is checked elsewhere
}
if _, err := strconv.ParseFloat(s, 64); err != nil {
if msg == "" {
return c.ΩT("Please enter a number.")
} else {
return v.Message
}
}
return
}
type MinFloatValidator struct {
MinValue float64
Message string
}
func (v MinFloatValidator) Validate(c page.ControlI, s string) (msg string) {
if s == "" {
return "" // empty textbox is checked elsewhere
}
if val, _ := strconv.ParseFloat(s, 64); val < v.MinValue {
if msg == "" {
return fmt.Sprintf(c.ΩT("Enter at least %f"), v.MinValue)
} else {
return v.Message
}
}
return
}
type MaxFloatValidator struct {
MaxValue float64
Message string
}
func (v MaxFloatValidator) Validate(c page.ControlI, s string) (msg string) {
if s == "" {
return "" // empty textbox is checked elsewhere
}
if val, _ := strconv.ParseFloat(s, 64); val < v.MaxValue {
if msg == "" {
return fmt.Sprintf(c.ΩT("Enter at most %f"), v.MaxValue)
} else {
return v.Message
}
}
return
}