-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathformvalidation.go
More file actions
196 lines (164 loc) · 5.62 KB
/
formvalidation.go
File metadata and controls
196 lines (164 loc) · 5.62 KB
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
package livetemplate
import (
"fmt"
"net/mail"
"net/url"
"regexp"
"strconv"
"strings"
"unicode/utf8"
)
// FormRule represents a validation rule inferred from HTML input attributes.
type FormRule struct {
Field string
Required bool
InputType string // "email", "url", "number", "tel"
MinLength int // -1 if not set
MaxLength int // -1 if not set
Min float64
Max float64
HasMin bool
HasMax bool
Pattern string // raw pattern string
PatternRe *regexp.Regexp // pre-compiled pattern (nil if invalid or absent)
}
// FormSchema holds validation rules inferred from template statics.
type FormSchema struct {
Rules []FormRule
}
// inputAttrRegex matches HTML input/textarea/select elements and captures their attributes.
var inputAttrRegex = regexp.MustCompile(`<(?:input|textarea|select)\b([^>]*)>`)
// attrRegex matches individual HTML attributes.
// Handles double-quoted values only. This is sufficient because Go's html/template
// always renders attributes with double quotes in statics.
var attrRegex = regexp.MustCompile(`(\w[\w-]*)(?:\s*=\s*"([^"]*)")?`)
// ExtractFormSchema scans template statics for HTML validation attributes
// on <input>, <textarea>, and <select> elements.
//
// Known limitation: if a field's name attribute is a template expression (dynamic),
// it will be split across statics and may not be detected.
func ExtractFormSchema(statics []string) *FormSchema {
schema := &FormSchema{}
fullHTML := strings.Join(statics, "")
matches := inputAttrRegex.FindAllStringSubmatch(fullHTML, -1)
for _, match := range matches {
attrs := parseHTMLAttributes(match[1])
name := attrs["name"]
if name == "" {
continue
}
rule := FormRule{
Field: name,
MinLength: -1,
MaxLength: -1,
}
if _, ok := attrs["required"]; ok {
rule.Required = true
}
if t, ok := attrs["type"]; ok {
rule.InputType = strings.ToLower(t)
}
if v, ok := attrs["minlength"]; ok {
if n, err := strconv.Atoi(v); err == nil {
rule.MinLength = n
}
}
if v, ok := attrs["maxlength"]; ok {
if n, err := strconv.Atoi(v); err == nil {
rule.MaxLength = n
}
}
if v, ok := attrs["min"]; ok {
if n, err := strconv.ParseFloat(v, 64); err == nil {
rule.Min = n
rule.HasMin = true
}
}
if v, ok := attrs["max"]; ok {
if n, err := strconv.ParseFloat(v, 64); err == nil {
rule.Max = n
rule.HasMax = true
}
}
if v, ok := attrs["pattern"]; ok {
rule.Pattern = v
// HTML pattern attribute implicitly anchors the full string (^...$)
rule.PatternRe, _ = regexp.Compile("^(?:" + v + ")$")
}
if rule.Required || rule.InputType == "email" || rule.InputType == "url" ||
rule.MinLength >= 0 || rule.MaxLength >= 0 || rule.HasMin || rule.HasMax || rule.Pattern != "" {
schema.Rules = append(schema.Rules, rule)
}
}
return schema
}
func parseHTMLAttributes(attrStr string) map[string]string {
attrs := make(map[string]string)
matches := attrRegex.FindAllStringSubmatch(attrStr, -1)
for _, m := range matches {
key := strings.ToLower(m[1])
val := m[2]
attrs[key] = val
}
return attrs
}
// Validate checks form data against the schema rules.
// Returns MultiError with field-level errors, or nil if valid.
func (s *FormSchema) Validate(data map[string]interface{}) error {
if s == nil || len(s.Rules) == 0 {
return nil
}
var errs MultiError
for _, rule := range s.Rules {
val, exists := data[rule.Field]
strVal := ""
if exists {
strVal = fmt.Sprintf("%v", val)
}
fieldName := formatFieldName(rule.Field)
if rule.Required && (!exists || strVal == "") {
errs = append(errs, FieldError{Field: toSnakeCase(rule.Field), Message: fmt.Sprintf("%s is required", fieldName)})
continue
}
if !exists || strVal == "" {
continue
}
if rule.InputType == "email" {
// HTML input[type=email] only accepts bare addr-spec (user@host), not display names.
addr, err := mail.ParseAddress(strVal)
if err != nil || addr.Address != strVal {
errs = append(errs, FieldError{Field: toSnakeCase(rule.Field), Message: fmt.Sprintf("%s must be a valid email address", fieldName)})
}
}
if rule.InputType == "url" {
u, err := url.Parse(strVal)
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
errs = append(errs, FieldError{Field: toSnakeCase(rule.Field), Message: fmt.Sprintf("%s must be a valid URL", fieldName)})
}
}
// Use rune count for minlength/maxlength (HTML counts Unicode code points, not bytes)
if rule.MinLength >= 0 && utf8.RuneCountInString(strVal) < rule.MinLength {
errs = append(errs, FieldError{Field: toSnakeCase(rule.Field), Message: fmt.Sprintf("%s must be at least %d characters", fieldName, rule.MinLength)})
}
if rule.MaxLength >= 0 && utf8.RuneCountInString(strVal) > rule.MaxLength {
errs = append(errs, FieldError{Field: toSnakeCase(rule.Field), Message: fmt.Sprintf("%s must be at most %d characters", fieldName, rule.MaxLength)})
}
if rule.HasMin || rule.HasMax {
if numVal, err := strconv.ParseFloat(strVal, 64); err == nil {
if rule.HasMin && numVal < rule.Min {
errs = append(errs, FieldError{Field: toSnakeCase(rule.Field), Message: fmt.Sprintf("%s must be at least %g", fieldName, rule.Min)})
}
if rule.HasMax && numVal > rule.Max {
errs = append(errs, FieldError{Field: toSnakeCase(rule.Field), Message: fmt.Sprintf("%s must be at most %g", fieldName, rule.Max)})
}
}
}
if rule.PatternRe != nil && !rule.PatternRe.MatchString(strVal) {
errs = append(errs, FieldError{Field: toSnakeCase(rule.Field), Message: fmt.Sprintf("%s is invalid", fieldName)})
}
}
if len(errs) > 0 {
return errs
}
return nil
}