...
1 package jsonschema
2
3 import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "regexp"
8 "unicode/utf8"
9
10 jptr "github.com/qri-io/jsonpointer"
11 )
12
13
14 type MaxLength int
15
16
17 func NewMaxLength() Keyword {
18 return new(MaxLength)
19 }
20
21
22 func (m *MaxLength) Register(uri string, registry *SchemaRegistry) {}
23
24
25 func (m *MaxLength) Resolve(pointer jptr.Pointer, uri string) *Schema {
26 return nil
27 }
28
29
30 func (m MaxLength) ValidateKeyword(ctx context.Context, currentState *ValidationState, data interface{}) {
31 schemaDebug("[MaxLength] Validating")
32 if str, ok := data.(string); ok {
33 if utf8.RuneCountInString(str) > int(m) {
34 currentState.AddError(data, fmt.Sprintf("max length of %d characters exceeded: %s", m, str))
35 }
36 }
37 }
38
39
40 type MinLength int
41
42
43 func NewMinLength() Keyword {
44 return new(MinLength)
45 }
46
47
48 func (m *MinLength) Register(uri string, registry *SchemaRegistry) {}
49
50
51 func (m *MinLength) Resolve(pointer jptr.Pointer, uri string) *Schema {
52 return nil
53 }
54
55
56 func (m MinLength) ValidateKeyword(ctx context.Context, currentState *ValidationState, data interface{}) {
57 schemaDebug("[MinLength] Validating")
58 if str, ok := data.(string); ok {
59 if utf8.RuneCountInString(str) < int(m) {
60 currentState.AddError(data, fmt.Sprintf("max length of %d characters exceeded: %s", m, str))
61 }
62 }
63 }
64
65
66 type Pattern regexp.Regexp
67
68
69 func NewPattern() Keyword {
70 return &Pattern{}
71 }
72
73
74 func (p *Pattern) Register(uri string, registry *SchemaRegistry) {}
75
76
77 func (p *Pattern) Resolve(pointer jptr.Pointer, uri string) *Schema {
78 return nil
79 }
80
81
82 func (p Pattern) ValidateKeyword(ctx context.Context, currentState *ValidationState, data interface{}) {
83 schemaDebug("[Pattern] Validating")
84 re := regexp.Regexp(p)
85 if str, ok := data.(string); ok {
86 if !re.Match([]byte(str)) {
87 currentState.AddError(data, fmt.Sprintf("regexp pattern %s mismatch on string: %s", re.String(), str))
88 }
89 }
90 }
91
92
93 func (p *Pattern) UnmarshalJSON(data []byte) error {
94 var str string
95 if err := json.Unmarshal(data, &str); err != nil {
96 return err
97 }
98
99 ptn, err := regexp.Compile(str)
100 if err != nil {
101 return err
102 }
103
104 *p = Pattern(*ptn)
105 return nil
106 }
107
108
109 func (p Pattern) MarshalJSON() ([]byte, error) {
110 re := regexp.Regexp(p)
111 rep := &re
112 return json.Marshal(rep.String())
113 }
114
View as plain text