-
Notifications
You must be signed in to change notification settings - Fork 2
/
validators.go
105 lines (78 loc) · 1.97 KB
/
validators.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
// Copyright 2011 The Walk Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package walk
import (
"errors"
"fmt"
"regexp"
)
type Validator interface {
Validate(v interface{}) error
}
type RangeValidator struct {
min float64
max float64
}
func NewRangeValidator(min, max float64) (*RangeValidator, error) {
if max <= min {
return nil, errors.New("max <= min")
}
return &RangeValidator{min: min, max: max}, nil
}
func (rv *RangeValidator) Min() float64 {
return rv.min
}
func (rv *RangeValidator) Max() float64 {
return rv.max
}
func (rv *RangeValidator) Validate(v interface{}) error {
f64 := v.(float64)
if f64 < rv.min || f64 > rv.max {
return errors.New(tr("The number is out of the allowed range.", "walk"))
}
return nil
}
type RegexpValidator struct {
re *regexp.Regexp
}
func NewRegexpValidator(pattern string) (*RegexpValidator, error) {
re, err := regexp.Compile(pattern)
if err != nil {
return nil, err
}
return &RegexpValidator{re}, nil
}
func (rv *RegexpValidator) Pattern() string {
return rv.re.String()
}
func (rv *RegexpValidator) Validate(v interface{}) error {
var matched bool
switch val := v.(type) {
case string:
matched = rv.re.MatchString(val)
case []byte:
matched = rv.re.Match(val)
case fmt.Stringer:
matched = rv.re.MatchString(val.String())
default:
panic("Unsupported type")
}
if !matched {
return errors.New(tr("The text does not match the required pattern.", "walk"))
}
return nil
}
type selectionRequiredValidator struct {
}
var selectionRequiredValidatorSingleton Validator = selectionRequiredValidator{}
func SelectionRequiredValidator() Validator {
return selectionRequiredValidatorSingleton
}
func (selectionRequiredValidator) Validate(v interface{}) error {
if v == nil {
// For Widgets like ComboBox nil is passed to indicate "no selection".
return errors.New(tr("A selection is required.", "walk"))
}
return nil
}