-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalidation.go
47 lines (38 loc) · 1.05 KB
/
validation.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
package errors
import (
"strings"
)
// NewValidationError returns a ValidationError instance with the provided parameters
func NewValidationError(field string, message string) error {
return wrap(&ValidationError{
Field: field,
Message: message,
}, 4)
}
// ValidationError represents an input validation error
type ValidationError struct {
Field string `json:"field_name,omitempty"`
Message string `json:"message,omitempty"`
Errors []ValidationError `json:"errors,omitempty"`
}
func (e *ValidationError) Error() string {
var builder = strings.Builder{}
if e.Field != "" {
builder.WriteString(e.Field)
builder.WriteString(": ")
}
builder.WriteString(e.Message)
for _, err := range e.Errors {
builder.WriteString("\n - ")
builder.WriteString(err.Error())
builder.WriteRune(';')
}
return builder.String()
}
// AddError adds a new validation error to the chain
func (e *ValidationError) AddError(field string, message string) {
e.Errors = append(e.Errors, ValidationError{
Field: field,
Message: message,
})
}