-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherrors.go
More file actions
72 lines (62 loc) · 1.66 KB
/
errors.go
File metadata and controls
72 lines (62 loc) · 1.66 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
package govalidate
import (
"fmt"
"strings"
)
// FieldError represents a validation error for a single field.
type FieldError struct {
Field string `json:"field"`
Rule string `json:"rule"`
Message string `json:"message"`
Value any `json:"value,omitempty"`
}
// Error returns a human-readable error string.
func (e FieldError) Error() string {
return fmt.Sprintf("%s: %s", e.Field, e.Message)
}
// ValidationError contains all field-level validation errors.
type ValidationError struct {
Errors []FieldError `json:"errors"`
}
// Error returns a combined error message.
func (ve ValidationError) Error() string {
if len(ve.Errors) == 0 {
return "validation passed"
}
msgs := make([]string, len(ve.Errors))
for i, e := range ve.Errors {
msgs[i] = e.Error()
}
return strings.Join(msgs, "; ")
}
// HasErrors returns true if there are any validation errors.
func (ve ValidationError) HasErrors() bool {
return len(ve.Errors) > 0
}
// FieldErrors returns all errors for a specific field.
func (ve ValidationError) FieldErrors(field string) []FieldError {
var result []FieldError
for _, e := range ve.Errors {
if e.Field == field {
result = append(result, e)
}
}
return result
}
// HasField returns true if the given field has validation errors.
func (ve ValidationError) HasField(field string) bool {
for _, e := range ve.Errors {
if e.Field == field {
return true
}
}
return false
}
// Map returns errors as a map of field name → error messages.
func (ve ValidationError) Map() map[string][]string {
result := make(map[string][]string)
for _, e := range ve.Errors {
result[e.Field] = append(result[e.Field], e.Message)
}
return result
}