summaryrefslogtreecommitdiff
path: root/form/errors.go
blob: ab9abd49cd29456f37f40afcad460424389d7fbc (plain)
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
package form

import (
	"errors"
	"fmt"
)

type FormErrors struct {
	Errors []error `form:"-"`
}

func (f *FormErrors) AddError(field, issue string) {
	f.Errors = append(f.Errors, FieldError{field, issue})
}

func (f *FormErrors) HasError() bool {
	return len(f.Errors) > 0
}

type FieldError struct {
	Field string
	Issue string
}

func (fe FieldError) Error() string {
	return fmt.Sprintf("%s: %v", fe.Field, fe.Issue)
}

// errors will build a map where each key is the field name, and each
// value is a slice of strings representing errors with that field.
func fieldErrors(errs []error) map[string][]string {
	ret := make(map[string][]string)
	for _, err := range errs {
		var fe FieldError
		if !errors.As(err, &fe) {
			fmt.Println(err, "isnt field error")
			continue
		}
		ret[fe.Field] = append(ret[fe.Field], fe.Issue)
	}
	return ret
}