github.com/volatiletech/authboss@v2.4.1+incompatible/defaults/validation.go (about) 1 package defaults 2 3 import ( 4 "fmt" 5 6 "github.com/volatiletech/authboss" 7 ) 8 9 // HTTPFormValidator validates HTTP post type inputs 10 type HTTPFormValidator struct { 11 Values map[string]string 12 13 Ruleset []Rules 14 ConfirmFields []string 15 } 16 17 // Validate validates a request using the given ruleset. 18 func (h HTTPFormValidator) Validate() []error { 19 var errList authboss.ErrorList 20 21 for _, rule := range h.Ruleset { 22 field := rule.FieldName 23 24 val := h.Values[field] 25 if errs := rule.Errors(val); len(errs) > 0 { 26 errList = append(errList, errs...) 27 } 28 } 29 30 if l := len(h.ConfirmFields); l != 0 && l%2 != 0 { 31 panic("HTTPFormValidator given an odd number of confirm fields") 32 } 33 34 for i := 0; i < len(h.ConfirmFields)-1; i += 2 { 35 main := h.Values[h.ConfirmFields[i]] 36 if len(main) == 0 { 37 continue 38 } 39 40 confirm := h.Values[h.ConfirmFields[i+1]] 41 if len(confirm) == 0 || main != confirm { 42 errList = append(errList, FieldError{h.ConfirmFields[i+1], fmt.Errorf("Does not match %s", h.ConfirmFields[i])}) 43 } 44 } 45 46 return errList 47 } 48 49 // FieldError represents an error that occurs during validation and is always 50 // attached to field on a form. 51 type FieldError struct { 52 FieldName string 53 FieldErr error 54 } 55 56 // NewFieldError literally only exists because of poor name planning 57 // where name and err can't be exported on the struct due to the method names 58 func NewFieldError(name string, err error) FieldError { 59 return FieldError{FieldName: name, FieldErr: err} 60 } 61 62 // Name of the field the error is about 63 func (f FieldError) Name() string { 64 return f.FieldName 65 } 66 67 // Err for the field 68 func (f FieldError) Err() error { 69 return f.FieldErr 70 } 71 72 // Error in string form 73 func (f FieldError) Error() string { 74 return fmt.Sprintf("%s: %v", f.FieldName, f.FieldErr) 75 }