Convert field errors into a selector for the object

Satisfies the "Field" condition for a Cause.  Also addresses
parts of #914.
This commit is contained in:
Clayton Coleman
2014-08-19 23:54:20 -04:00
parent d326ba2976
commit 84db1da42b
3 changed files with 141 additions and 63 deletions

View File

@@ -106,7 +106,7 @@ func NewNotFound(field string, value interface{}) ValidationError {
// the ToError() method, which will return nil for an empty ErrorList.
type ErrorList []error
// This helper implements the error interface for ErrorList, but must prevents
// This helper implements the error interface for ErrorList, but prevents
// accidental conversion of ErrorList to error.
type errorListInternal ErrorList
@@ -129,3 +129,27 @@ func (list ErrorList) ToError() error {
}
return errorListInternal(list)
}
// Prefix adds a prefix to the Field of every ValidationError in the list. Returns
// the list for convenience.
func (list ErrorList) Prefix(prefix string) ErrorList {
for i := range list {
if err, ok := list[i].(ValidationError); ok {
if strings.HasPrefix(err.Field, "[") {
err.Field = prefix + err.Field
} else if len(err.Field) != 0 {
err.Field = prefix + "." + err.Field
} else {
err.Field = prefix
}
list[i] = err
}
}
return list
}
// PrefixIndex adds an index to the Field of every ValidationError in the list. Returns
// the list for convenience.
func (list ErrorList) PrefixIndex(index int) ErrorList {
return list.Prefix(fmt.Sprintf("[%d]", index))
}