github.com/volatiletech/authboss@v2.4.1+incompatible/validation.go (about)

     1  package authboss
     2  
     3  import (
     4  	"bytes"
     5  )
     6  
     7  const (
     8  	// ConfirmPrefix is prepended to names of confirm fields.
     9  	ConfirmPrefix = "confirm_"
    10  )
    11  
    12  // Validator takes a form name and a set of inputs and returns any
    13  // validation errors for the inputs.
    14  type Validator interface {
    15  	// Validate makes the type validate itself and return
    16  	// a list of validation errors.
    17  	Validate() []error
    18  }
    19  
    20  // FieldError describes an error on a field
    21  // Typically .Error() has both Name() and Err() together, hence the reason
    22  // for separation.
    23  type FieldError interface {
    24  	error
    25  	Name() string
    26  	Err() error
    27  }
    28  
    29  // ErrorMap is a shortcut to change []error into ErrorList and call Map on it
    30  // since this is a common operation.
    31  func ErrorMap(e []error) map[string][]string {
    32  	return ErrorList(e).Map()
    33  }
    34  
    35  // ErrorList is simply a slice of errors with helpers.
    36  type ErrorList []error
    37  
    38  // Error satisfies the error interface.
    39  func (e ErrorList) Error() string {
    40  	b := &bytes.Buffer{}
    41  	first := true
    42  	for _, err := range e {
    43  		if first {
    44  			first = false
    45  		} else {
    46  			b.WriteString(", ")
    47  		}
    48  		b.WriteString(err.Error())
    49  	}
    50  	return b.String()
    51  }
    52  
    53  // Map groups errors by their field name
    54  func (e ErrorList) Map() map[string][]string {
    55  	m := make(map[string][]string)
    56  
    57  	for _, err := range e {
    58  		fieldErr, ok := err.(FieldError)
    59  		if !ok {
    60  			m[""] = append(m[""], err.Error())
    61  		} else {
    62  			name, err := fieldErr.Name(), fieldErr.Err()
    63  			m[name] = append(m[name], err.Error())
    64  		}
    65  	}
    66  
    67  	return m
    68  }