-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathboolean.go
76 lines (63 loc) · 1.58 KB
/
boolean.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
package vjson
import (
"encoding/json"
"github.com/pkg/errors"
)
// BooleanField is the type for validating booleans in a JSON
type BooleanField struct {
name string
required bool
valueValidation bool
value bool
}
// To Force Implementing Field interface by BooleanField
var _ Field = (*BooleanField)(nil)
// GetName returns name of the field
func (b *BooleanField) GetName() string {
return b.name
}
// Validate is used for validating a value. it returns an error if the value is invalid.
func (b *BooleanField) Validate(v interface{}) error {
if v == nil {
if !b.required {
return nil
}
return errors.Errorf("Value for %s field is required", b.name)
}
value, ok := v.(bool)
if !ok {
return errors.Errorf("Value for %s should be a boolean", b.name)
}
if b.valueValidation {
if value != b.value {
return errors.Errorf("Value for %s should be a %v", b.name, b.value)
}
}
return nil
}
// Required is called to make a field required in a JSON
func (b *BooleanField) Required() *BooleanField {
b.required = true
return b
}
// ShouldBe is called for setting a value for checking a boolean.
func (b *BooleanField) ShouldBe(value bool) *BooleanField {
b.value = value
b.valueValidation = true
return b
}
func (b *BooleanField) MarshalJSON() ([]byte, error) {
return json.Marshal(BooleanFieldSpec{
Name: b.name,
Type: booleanType,
Required: b.required,
Value: b.value,
})
}
// Boolean is the constructor of a boolean field
func Boolean(name string) *BooleanField {
return &BooleanField{
name: name,
required: false,
}
}