1
0
mirror of https://github.com/astaxie/beego.git synced 2024-11-25 02:30:55 +00:00

validation: fix ErrorMap, added func AddError(key, message)

This commit is contained in:
Radar8 2017-09-06 16:49:21 +08:00
parent d96289a81b
commit 6641a436a2

View File

@ -112,7 +112,7 @@ type Validation struct {
RequiredFirst bool RequiredFirst bool
Errors []*Error Errors []*Error
ErrorsMap map[string]*Error ErrorsMap map[string][]*Error
} }
// Clear Clean all ValidationError. // Clear Clean all ValidationError.
@ -129,7 +129,7 @@ func (v *Validation) HasErrors() bool {
// ErrorMap Return the errors mapped by key. // ErrorMap Return the errors mapped by key.
// If there are multiple validation errors associated with a single key, the // If there are multiple validation errors associated with a single key, the
// first one "wins". (Typically the first validation will be the more basic). // first one "wins". (Typically the first validation will be the more basic).
func (v *Validation) ErrorMap() map[string]*Error { func (v *Validation) ErrorMap() map[string][]*Error {
return v.ErrorsMap return v.ErrorsMap
} }
@ -278,14 +278,35 @@ func (v *Validation) apply(chk Validator, obj interface{}) *Result {
} }
} }
// Add independent error message for key
func (v *Validation) AddError(key, message string) {
Name := key
Field := ""
parts := strings.Split(key, ".")
if len(parts) == 2 {
Field = parts[0]
Name = parts[1]
}
err := &Error{
Message: message,
Key: key,
Name: Name,
Field: Field,
}
v.setError(err)
}
func (v *Validation) setError(err *Error) { func (v *Validation) setError(err *Error) {
v.Errors = append(v.Errors, err) v.Errors = append(v.Errors, err)
if v.ErrorsMap == nil { if v.ErrorsMap == nil {
v.ErrorsMap = make(map[string]*Error) v.ErrorsMap = make(map[string][]*Error)
} }
if _, ok := v.ErrorsMap[err.Field]; !ok { if _, ok := v.ErrorsMap[err.Field]; !ok {
v.ErrorsMap[err.Field] = err v.ErrorsMap[err.Field] = []*Error{}
} }
v.ErrorsMap[err.Field] = append(v.ErrorsMap[err.Field], err)
} }
// SetError Set error message for one field in ValidationError // SetError Set error message for one field in ValidationError